![](/img/trans.png)
[英]check if a string from a file exists in a list of list of strings: 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"
两个词不在句子中,但无论如何它都会返回True
。 相反,如果你想检查单词,你应该使用:
any(w in sentence.lower().split(' ') for w in words)
使用这个场景。
a="Hello Moto"
a.find("Hello")
它会给你一个索引作为回报。 如果字符串不存在,它将返回 -1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.