Find sum of matching words in sentence according to list of words

Issue

I have data containing two variables (sentence and b), like this. I want to find the sum of words in b according to the sentence. Then i save in sum variable

          sentence                        b
i like coffee better than tea        'coffee', 'tea'
because coffee can make me stay 
happy

I want the output like this, any two words of coffee in the sentence and one word of tea in the sentence so the sum of words is three that i save in sum variable.

          sentence                        b                    sum
i like coffee better than tea        'coffee', 'tea'            3
because coffee can make me stay 
happy

anyone can help me?

Solution

Use the str.count() function, it returns the number of occurrence of the provided substring in a string.

for i in b:
    sumOfWords += sentence.count(i)

Answered By – kelvinC

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published