Home > Software engineering >  Find sum of matching words in sentence according to list of words
Find sum of matching words in sentence according to list of words

Time:06-10

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?

CodePudding user response:

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)
  • Related