我在Python脚本中遇到了一个问题,我需要做的是,拆分函数的索引,会随着循环的每次迭代而自动增加。我这样做:
tag = "\'"
while loop<=302:
for line in f1.readlines():
if tag in line:
word = line.split(tag)[num] #num is the index I need to increase
text = "Word: "+word+"."
f.write(text)
num = num + 1
loop = loop + 1索引上的But...the“change...it”变量不会简单地保持不变。num索引指示我需要获取的单词。这就是为什么"num = num + 1“必须增加...
循环中的问题是什么?
谢谢!
发布于 2013-03-02 02:13:57
你的问题令人困惑。但我认为您应该将num = num + 1移到for循环和if语句中。
tag = "\'"
while loop<=302:
for line in f1.readlines():
if tag in line:
word = line.split(tag)[num] #num is the index I need to increase
num = num + 1
text = "Word: "+word+"."
f.write(text)
loop = loop + 1发布于 2013-03-02 02:21:11
基于Benyi在问题中的评论-你只想在单个句子中使用这个吗?您可能不需要索引。
>>> mystring = 'hello i am a string'
>>> for word in mystring.split():
print 'Word: ',word
Word: hello
Word: i
Word: am
Word: a
Word: string发布于 2013-03-02 02:21:54
这似乎有很多地方不对劲。
第一
while loop <= 302:
for line in f1.readlines():对于第一个迭代之后的每个迭代,f1.readines()将为[]
第二
for line in f1.readline():
word = line.split(tag)[num]
...
text = "Word: "+word+"."即使您使for循环工作,text也将始终使用word的最后一次迭代。也许这是我们想要的行为,但它看起来很奇怪。
第三
while loop<=302:
...
loop = loop += 1看起来更好的写法是
for _ in xrange(302):因为在作用域中根本不使用循环。这是假设循环从0开始,如果不是,那么你只需将302调整为你想要的迭代次数。
最后
num = num + 1这是在你的内部循环之外,所以num在第一次迭代中总是相同的,之后就不会有问题了,因为前面提到的f1.readlines()是空的。
https://stackoverflow.com/questions/15164142
复制相似问题