Skip to main content
 首页 » 编程设计

python之python 中的嵌套 for 循环不会增加外部 for 循环

2025年05月04日38findumars

我有两个文件:q.txt 包含单词,p.txt 包含句子。我需要检查 p.txt 中是否存在 q.txt 中的任何单词。以下是我写的:

#!/usr/bin/python 
twts=open('p.txt','r'); 
words=open('q.txt','r'); 
for wrd in words: 
        for iter in twts: 
                if (wrd in iter): 
                        print "Found at line" +iter 

即使匹配也不会打印输出。我还可以看到外部 for 循环不会继续处理 words 对象中的下一个值。有人可以解释一下我在这里做错了什么吗?

编辑 1:我使用的是 Python 2.7 编辑 2:对不起,我混淆了变量名。现已更正。

请您参考如下方法:

当你迭代一个文件对象时,在完成迭代后,光标最终会到达文件的末尾。因此,尝试再次迭代它(在外层 for 循环的下一次迭代中)是行不通的。让代码工作的最简单方法是在外部 for 循环的开头查找文件的开头。示例 -

#!/usr/bin/python 
words=open('q.txt','r'); 
twts=open('p.txt','r'); 
for wrd in words: 
    twts.seek(0) 
    for twt in twts: 
        if (wrd.strip() in twt): 
            print "Found at line" +iter 

此外,根据问题,您似乎使用了错误的文件,twts 应该是带有句子的文件,words 应该是带有单词的文件。但是您已经为 words 打开了 p.txt,为 `sentences 打开了 q.txt。如果相反,您应该以相反的方式打开文件。

此外,建议不要将 iter 用作变量名,因为它也是内置函数的名称,并且您将其定义在 - for iter in twts - 隐藏内置函数 - iter() 。