我正在使用 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")
最佳答案
最好习惯使用 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')
关于python - 检查文本文件python中是否存在单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44205923/