Python 检查字符串列表中的句子中是否存在某个字符串

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

我有一个像 substring = ["one","multiple words"] 这样的单词列表,我想从中检查一个句子是否包含这些单词中的任何一个。

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

我要使用任何运算符检查的代码:

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

即使这个词出现在我的句子中,这也会给我错误。我不想使用正则表达式,因为它对大量数据来说是一项昂贵的操作。

还有其他方法吗?

我认为你应该取消订单:

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

您正在检查您的子字符串是否是您句子的一部分,而不是您的句子是否是您任何子字符串的一部分。

如其他答案中所述,如果您想检测子字符串,这将为您提供正确答案:

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

但是,如果您的目标是查找单词而不是子字符串,这是不正确的。考虑:

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

"air""hi" 这两个词不在句子中,但 returns True 无论如何。相反,如果你想检查单词,你应该使用:

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

使用这个场景。

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

它将在 return 中为您提供一个索引。如果字符串不存在,它将 return -1