I have a list of of words which I want to find in a text file.
Right now I'm trying the any
method to iterate through lines in a file.
It returns True
or False
correctly so it's working fine.
My question though is if it's possible to see which word it found? I can see with my code and the text which word was found but I would like to use it in the code somehow if it's possible.
An example of what I mean below. This code returns True
or False
if any of the words are in the line
.
list_of_words = ['apple', 'banana', 'lemon']
with open(file, 'r') as f:
lines = f.readlines()
for line in lines:
x = any(word in line for word in list_of_words)
print(x)
You can use next
instead, with a default
in case no element is found.
x = next((word for word in list_of_words if word in line), None)
if x is not None:
...
If None
can be an element in the list, you may use some dedicated sentinel object instead, e.g.
not_in = object()
x = next((word for word in list_of_words if word in line), not_in)
if x is not not_in:
...
Or explicitly catch the StopIteration
error:
try:
x = next(word for word in list_of_words if word in line)
...
except StopIteration:
pass
Note that all of these approaches only give you the first such element, and then stop checking the rest (like any
does); if instead you are interested in all such elements, you should use a list comprehension as in the other answer.