简体   繁体   中英

Python Check if a string is there in a sentence from a list of strings

I have a list of words like substring = ["one","multiple words"] from which i want to check if a sentence contains any of these words.

sentence1 = 'This Sentence has ONE word'
sentence2 = ' This sentence has Multiple Words'

My code to check using any operator:

any(sentence1.lower() in s for s in substring)

This is giving me false even if the word is present in my sentence. I don't want to use regex as it would be an expensive operation for huge data.

Is there any other approach to this?

I think you should reverse your order:

any(s in sentence1.lower() for s in substring)

you're checking if your substring is a part of your sentence, NOT if your sentence is a part of any of your substrings.

As mentioned in other answers, this is what will get you the correct answer if you want to detect substrings:

any(s in sentence1.lower() for s in substring)

However, if your goal is to find words instead of substrings, this is incorrect. Consider:

sentence = "This is an aircraft"
words = ["air", "hi"]
any(w in sentence.lower() for w in words)  # True.

The words "air" and "hi" are not in the sentence, but it returns True anyway. Instead, if you want to check for words, you should use:

any(w in sentence.lower().split(' ') for w in words)

use this scenario.

a="Hello Moto"
    a.find("Hello")

It will give you an index in return. If the string is not there it will return -1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM