CodeLikeBeaker
CodeLikeBeaker

Reputation: 21312

Get keywords in a string from a list of strings in Python

Note, this is not a duplicate of this question:

How to check if a string contains an element from a list in Python

However, it's based on it's logic.

I have the following string:

my_string = 'this is my complex description'

I have a list of keywords:

keywords = ['my', 'desc', 'complex']

I know I can use the following to check if the keywords exist:

if any(ext in my_string for ext in keywords):
    print(my_string)

But I'd like to show which keywords actually match the description. I know I can do a loop through the keywords, and then do a check for each one individually, but is it possible in a single statement?

It doesn't matter which version of python is the solution.

Upvotes: 1

Views: 2804

Answers (3)

Chad S.
Chad S.

Reputation: 6633

found_words = [ word for word in keywords if word in my_string ]

This will give you a list of the keywords that are found in my_string. Performance will be better if you make keywords a set though:

keywords = set(['my', 'desc', 'complex'])
found_words = [ word for word in my_string.split() if word in keywords ]

But the latter relies on the fact that my_string doesn't separate words with anything other than whitespace.

Upvotes: 1

Eugene Yarmash
Eugene Yarmash

Reputation: 149726

If you want to match complete words, you could use set intersection:

>>> my_string = 'this is my complex description'
>>> keywords = ['my', 'desc', 'complex']
>>> set(my_string.split()) & set(keywords)
{'complex', 'my'}

Upvotes: 4

R Nar
R Nar

Reputation: 5515

>>> my_string = 'this is my complex description'
>>> keywords = ['my', 'desc', 'complex']
>>> print(*[c for c in my_string.split() if c in keywords])
my complex

Note this this only works, to my knowledge, on python3.x (I am not too sure about how it would stand in python 2)

If you're confused on what it is doing, the * is just unpacking the list made from a list comprehension that filters any item that ISNT in my_string as separate arguments in print. In python3, separate args in print are printed with spaces in between them.

Upvotes: 1

Related Questions