count number of words occurrence in text based on list of string

Question:

I want to know what is the best approach to find the number of occurrence in text based on list of string. I found some use sum(any()) but it didn’t work because if text contains "re" it will count it

list1 = ['red', 'green', 'amazing', 'orange', 'amazing color', 'gray', 'pink']

text="green and red is an amazing color "

The expect count is 4

Thank you

Asked By: John

||

Answers:

Probably there is a much smoother way, but the simple for-loop does the job.

list1 = ['red', 'green', 'amazing', 'orange', 'amazing color', 'gray', 'pink']

text="green and red is an amazing color "

amount_words_from_list_in_text = 0

for word in list1:
    if word in text:
        amount_words_from_list_in_text += 1

print(amount_words_from_list_in_text)
Answered By: Jacob

All you need to do is use the built-in sum() function along with str.count() and a generator expression:

sum(text.count(item) for item in list1)
Answered By: MattDMo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.