I have a list of strings in which I want to filter for strings that contains keywords.
I want to do something like:
fruit = re.compile(\'apple\', \'
As you want exact matches, no real need for regex imo...
fruits = ['apple', 'cherry']
sentences = ['green apple', 'yellow car', 'red cherry']
for s in sentences:
if any(f in s for f in fruits):
print s, 'contains a fruit!'
# green apple contains a fruit!
# red cherry contains a fruit!
EDIT: If you need access to the strings that matched:
from itertools import compress
fruits = ['apple', 'banana', 'cherry']
s = 'green apple and red cherry'
list(compress(fruits, (f in s for f in fruits)))
# ['apple', 'cherry']