我正在使用 Python,我试图找出文本文件中是否有一个单词。我正在使用此代码,但它总是打印“找不到单词”,我认为该条件存在一些逻辑错误,如果您能更正此代码,请任何人:
file = open("search.txt")
print(file.read())
search_word = input("enter a word you want to search in file: ")
if(search_word == file):
print("word found")
else:
print("word not found")
Run Code Online (Sandbox Code Playgroud)
Bil*_*ell 10
更好的是,您应该习惯于with在打开文件时使用它,以便在您使用完后它会自动关闭。但主要是用来in在另一个字符串中搜索一个字符串。
with open('search.txt') as file:
contents = file.read()
search_word = input("enter a word you want to search in file: ")
if search_word in contents:
print ('word found')
else:
print ('word not found')
Run Code Online (Sandbox Code Playgroud)
其他选择,您可以search在读取文件本身时:
search_word = input("enter a word you want to search in file: ")
if search_word in open('search.txt').read():
print("word found")
else:
print("word not found")
Run Code Online (Sandbox Code Playgroud)
为了缓解可能的内存问题,请使用mmap.mmap()此处回答的相关问题
以前,您在文件变量“open("search.txt")”中进行搜索,由于该变量不在您的文件中,因此您会收到“未找到单词”的信息。
您还询问搜索词是否与 'open("search.txt")' 完全匹配,因为 == 。不要使用 ==,而使用“in”。尝试:
file = open("search.txt")
strings = file.read()
print(strings)
search_word = input("enter a word you want to search in file: ")
if(search_word in strings):
print("word found")
else:
print("word not found")
Run Code Online (Sandbox Code Playgroud)