问题
I'm working with Python, and I'm trying to find out if a word is in a text file. i am using this code but it always print the "word not found", i think there is some logical error in the condition, anyone please if you can correct this code:
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")
回答1:
Better you should become accustomed to using with
when you open a file, so that it's automatically close when you've done with it. But the main thing is to use in
to search for a string within another string.
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')
回答2:
Other alternative, you can search
while reading a file itself:
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")
To alleviate the possible memory problems, use mmap.mmap()
as answered here related question
回答3:
Previously, you were searching in the file variable, which was 'open("search.txt")' and since that wasn't in your file, you were getting word not found.
You were also asking if the search word exactly matched 'open("search.txt")' because of the ==. Don't use ==, use "in" instead. Try:
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")
来源:https://stackoverflow.com/questions/44205923/checking-if-word-exists-in-a-text-file-python