You could use re.findall()
to extract all the words from the sentences in description
, and check if any of the words from my_list
exist in it:
import re
def find_words(words, text):
desc_words = re.findall(r'[^\s,.]+', "".join(text))
for word in words:
if word in desc_words:
return "found"
return "Keywords not found"
Which outputs:
>>> description = ['This is a random sentence. I like to travel and stuff','Hello world', 'Things on my bucket list, travel']
>>> my_list = ['travel','fire']
>>> find_words(my_list, description)
found
Or you could use this set()
approach:
def find_words(words, text):
return "found" if set(words).intersection(re.findall(r'[^\s,.]+', "".join(text))) else "Keywords not found"
Note: You will have to update your regular expression if you come across sentences with different punctuation other than ,.
.