Python检查字符串列表中的句子中是否有字符串

2024-04-19 19:30:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个像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)

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

还有其他方法吗


Tags: in列表substringmultiplethis单词onesentence
3条回答

我认为你应该颠倒你的顺序:

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

你是在检查你的子串是否是句子的一部分,而不是你的句子是否是任何子串的一部分

使用此场景

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

它会给你一个索引作为回报。如果字符串不在那里,它将返回-1

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

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"不在句子中,但它仍然返回True。相反,如果要检查单词,应使用:

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

相关问题 更多 >