MiQ
MiQ

Reputation: 39

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?

Upvotes: 0

Views: 65

Answers (2)

stumbi
stumbi

Reputation: 1

It won't work with the .split() function, because you will get a list containing all singular words. What you can do, is checking if every element in your list is in your String and if so, you can save it. With a simple loop like for i in flat_list: if i in description: keys.append(i)

I haven't checked it, but I'm quit sure it works, or at least you will get an idea how you migth proceed.

Upvotes: 0

CopyrightC
CopyrightC

Reputation: 863

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

Upvotes: 1

Related Questions