python – Check list of words in another string

python – Check list of words in another string

if any(word in some one long two phrase three for word in list_):

If your list of words is of substantial length, and you need to do this test many times, it may be worth converting the list to a set and using set intersection to test (with the added benefit that you wil get the actual words that are in both lists):

>>> long_word_list = some one long two phrase three about above along after against
>>> long_word_set = set(long_word_list.split())
>>> set(word along river.split()) & long_word_set

python – Check list of words in another string

Here are a couple of alternative ways of doing it, that may be faster or more suitable than KennyTMs answer, depending on the context.

1) use a regular expression:

import re
words_re = re.compile(|.join(list_of_words))

if one long two phrase three):
   # do logic you want to perform

2) You could use sets if you want to match whole words, e.g. you do not want to find the word the in the phrase them theorems are theoretical:

word_set = set(list_of_words)
phrase_set = set(some one long two phrase three.split())
if word_set.intersection(phrase_set):
    # do stuff

Of course you can also do whole word matches with regex using the b token.

The performance of these and Kennys solution are going to depend on several factors, such as how long the word list and phrase string are, and how often they change. If performance is not an issue then go for the simplest, which is probably Kennys.

Leave a Reply

Your email address will not be published. Required fields are marked *