0

I am trying to find if the words/string in the list are present in a given sentence.

sentence = 'The total number of cases in germany is equal to the inital cases from china'
listA = []
listA.append('equal to')
listA.append('good')
listA.append('case')


for item in listA:
    if item in sentence.lower().strip():
       print('success')
    else:
        print('Not Present')

I also tried with

if item in sentence.lower():

and

if item in sentence.lower().split():

But, this captures also the phrase cases or does not work for phrases

Betafish
  • 1,212
  • 3
  • 20
  • 45
  • You have to split the `sentence` into a list of words before using `in`. – stovfl Apr 20 '20 at 10:58
  • 1
    You can do one thing, attach spaces at front and end of the words in the list and then do the same what you've done. – Strange Apr 20 '20 at 10:58
  • Does this answer your question? [String exact match](https://stackoverflow.com/questions/4173787/string-exact-match) – Vikas Mulaje Apr 20 '20 at 11:00
  • Spaces aren't the way forward @strange.....unless you add a space to the sentence's start and end too. Word boundaries is what you want instead =) – JvdV Apr 20 '20 at 11:05

2 Answers2

3

This thing checks for a substring, so any correct character sequence, no matter whether they are in the middle of word of not.

What you need is regex search - regex has a special character to mean "word boundary" - \b:

import re
for item in listA:
    if re.search(r"\b{}\b".format(item), sentence.lower().strip()):
        print('success')
    else:
        print('Not Present')
h4z3
  • 5,265
  • 1
  • 15
  • 29
0

Add spaces at front and end of the word and then check using the same code you've used.

for item in listA:
    if ' '+item+' ' in sentence.lower():
       print('success')
    else:
        print('Not Present')
Strange
  • 1,460
  • 1
  • 7
  • 18