简体   繁体   English

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

[英]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.我有一个像substring = ["one","multiple 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. "air""hi"两个词不在句子中,但无论如何它都会返回True 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如果字符串不存在,它将返回 -1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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