检查文本文件python中是否存在word

2024-04-20 06:10:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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")

Tags: 代码txtreadinputsearch错误情况逻辑
3条回答

最好你应该习惯于在打开文件时使用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')

另一种选择是,您可以在读取文件本身时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")

要缓解可能的内存问题,请使用这里所回答的mmap.mmap()related question

以前,您在文件变量中搜索,该变量为“open(“search.txt”)”,由于该变量不在您的文件中,因此您得到的是word not found。

您还询问搜索词是否与“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")

相关问题 更多 >