将列表中的单词与文件中的单词进行比较

时间:2014-01-25 22:02:39

标签: python

我正在尝试编写一个循环遍历列表的程序,并检查文件以查看该单词是否在那里。首先,读取文件,然后如果找到一个单词,它就会突破该循环。找到该单词后文件中的其余行,我想与列表进行比较。以下代码无效。它只是突破循环而没有找到这个词。 谢谢你的协助。

def readFile():
with open("file.txt", "r") as myfile:
    for line in myfile:
        if "Hello" in line:
            break
    for word in mylist:
        if word in myfile:
           print(word + "found")

1 个答案:

答案 0 :(得分:2)

您需要另一个for line in myfile循环。你不能if word in myfile检查整个文件,你仍然需要遍历每一行。

with open("file.txt", "r") as myfile:
    for line in myfile:
        if "Hello" in line:
            break
    for line in myfile:
        for word in mylist:
            if word in line:
                print(word + "found")

请注意,这可能会多次打印相同的单词。如果你不想要,你需要跟踪你已经看过的单词。

already_seen = set()        

for line in myfile:
    for word in mylist:
        if word in already_seen:
            continue

        if word in line:
            print(word + "found")
            already_seen.add(word)