'Along with the word, the script also searches for parts of the word
My script finds other words along with the word like apple, such as app, me, ple, appl, etc. which in the search_word, but i don't want it, i need the script to define only the complete word which in the contents but not its parts.
apple - yes, i want to define this word.
app - no, i don't want to define this word.
list.txt contains:
apple
code:
with open('list.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')
this not work:
if search_word == contents:
Solution 1:[1]
This:
if search_word in contents:
Just change to:
if any(search_word==word.strip() for word in contents.split())
Thanks to the contribution in the comments!
Solution 2:[2]
You may split the text using the space to avoid partial matching.
text_list = contents.split()
if search_word in text_list:
print ('word found')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SkruDJ |
| Solution 2 | Esraa Abdelmaksoud |
