首页 > 解决方案 > 在txt文档中搜索单词,python

问题描述

我有这个简单的代码,它读取一个 txt 文件并接受用户的一个词来检查该词是否在 txt 文档中。看起来这只适用于一个单词。我必须修改此代码,以便用户可以输入两个或更多单词。例子; GOING HOME而不仅仅是HOME. 请提供任何帮助。

word = input('Enter any word that you want to find in text File :')
f = open("AM30.EB","r")
if word in f.read().split():
    print('Word Found in Text File')
else:
    print('Word not found in Text File')

标签: pythonpython-3.x

解决方案


我不确定这正是您正在寻找的

f = open("AM30.EB","r")

word_list = []

while True:
    word = input('Enter any word that you want to find in text File or 1 to stop entering words :')
    if word == "1": break
    word_list.append(word)

file_list = f.read().split()

for word in word_list:
    if word in file_list:
        print("Found word - {}".format(word))
    

推荐阅读