0
with open(sys.argv[2]) as f:
     processlist = f.readlines()
     for a in range(0,1):
         process = processlist[a]
         print process
         for b in range(0,3):
             process1 = process.split()
             print process1[b]

sys.argy[2] 文件只有 2 个句子

Sunday Monday
local owner public

我试图一次读一个句子,在每个句子中我试图一次访问一个单词......我能够单独获得我需要的东西,但循环不会迭代......它第一次迭代后停止....

4

2 回答 2

3
with open(sys.argv[2]) as f:
    for line in f: #iterate over each line
        #print("-"*10) just for demo
        for word in line.rstrip().split(): #remove \n then split by space
            print(word)

在你的文件上会产生

----------
Sunday
Monday
----------
local
owner
public
于 2013-05-13T07:39:04.250 回答
2

To answer your question why the loop doesn't iterate:

range(0,1)

contains only the element 0, since the upper bound is not included in the result. Similarly,

range(0,5)

would, when viewed as a list, be [0,1,2,3,4].

The correct way to iterate over a file is demonstrated by @HennyH's answer.

于 2013-05-13T07:55:57.203 回答