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

标签 python for-loop nested

我有两个文件: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()

关于python - python 中的嵌套 for 循环不会增加外部 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32546695/

相关文章:

python - 如何在 openpyxl 中应用条件格式?

java - Android - 具有嵌套信息和数组的 GenericJson

java - 如何在嵌套集合中添加内部映射?

c++ - (C++) For 循环 - 为什么要这样做?

Android Espresso - 嵌套 parent 的组合 View 匹配器

python - 成功创建 super 用户后无法登录 Heroku 管理面板

Python; BeautifulSoup 和内置函数

python - 是什么导致 ColumnTransformer 出现这种奇怪的行为? [Python/sklearn]

python - 根据重复值将字典列表合并为较小的字典列表

c - y = x++ <= 2 在 C 中是什么意思?