Skip to content
Advertisement

How to check if a string contains item(s) from a list and then add the existing values to a variable in python?

I have imported a .csv file as a flat list which contains keywords that should be added to same variable if they exist in description variable (string).

with open(keywordsPath, newline='') as csvfile: # Import csv file
data = list(csv.reader(csvfile)) # Add csv file contents to a list


flat_list = [item for sublist in data for item in sublist]

I already have come up with a method to check what items from the list exist in the description string, but the problem is that it can’t check for keywords that have more than one word in them:

description = 'Some one word keywords and some two word keywords'
# flat_list contents: ['one', 'keywords', 'two word']
#
keys = ''

for i in flat_list: 
    if i in description.split():
        keys = (keys + i + ', ')
if keys.endswith(', '):
    keys = keys.rstrip(', ').title()
print(keys)
>> One, Keywords

So in this example I would like the variable “keys” also include “two word”. How should I do that?

Advertisement

Answer

You don’t need to use .split()

for i in flat_list: 
    if i in description:
        #[...]
description = 'Some one word keywords and some two word keywords'
flat_list  = ['one', 'keywords', 'two word',"blah blah", "one more item"]
>>> One, Keywords, Two Word
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement