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

Python 将列表中的单词与文件中的单词进行比较,python,Python,我正试图编写一个程序,循环遍历一个列表并检查一个文件,看看那个单词是否在其中。首先,读取文件,然后如果找到一个单词,它就会跳出该循环。在找到该单词后,我想将文件中的其余行与列表进行比较。下面的代码不起作用。它只是跳出循环,找不到单词。 谢谢你的帮助 def readFile(): with open("file.txt", "r") as myfile: for line in myfile: if "Hello" in line: break

我正试图编写一个程序,循环遍历一个列表并检查一个文件,看看那个单词是否在其中。首先,读取文件,然后如果找到一个单词,它就会跳出该循环。在找到该单词后,我想将文件中的其余行与列表进行比较。下面的代码不起作用。它只是跳出循环,找不到单词。 谢谢你的帮助

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")

在myfile循环中,需要为行添加另一个
。如果myfile中的word要检查整个文件,您不能执行
,您仍然需要在每一行上循环

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)

或者,对于第二部分,更简单(可能更实用,尤其是对于小列表)
seen=set(mylist)。交叉点(myfile)
-然后在末尾打印。。。