Python检查字符串是否包含lis中的任何元素

2024-09-28 01:30:17 发布

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

我需要检查字符串是否包含列表中的任何元素。我正在使用此方法:

engWords = ["the", "a", "and", "of", "be", "that", "have", "it", "for", "not"]
engSentence = "the dogs fur is black and white"

print("the english sentence is: " + engSentence)

engWords2 = []
isEnglish = 0

for w in engWords:
    if w in engSentence:
        isEnglish = 1
        engWords2.append(w)

if isEnglish == 1:
    print("The sentence is english and contains the words: ")
    print(engWords2)

问题在于它给出的输出是:

^{pr2}$

如你所见,a和it不应该出现。我怎样才能搜索到它只列出单个单词,而不是一个单词的一部分?我愿意接受任何使用普通python代码或regex的想法(尽管我对python和regex都很陌生,所以请不要太复杂)谢谢。在


Tags: andtheinforifenglishisit
3条回答
words = set(engSentence.split()).intersection(set(engWords))
if words:
    print("The sentence is english and contains the words: ")
    print(words)

将英语句子拆分成一个列表中的标记,将其转换为集合,将英语单词转换为集合,然后找到交集(公共重叠)。然后检查这是否是非空的,如果是,打印出找到的单词。在

找到这两个词是因为它们分别是“黑”和“白”的子串。将“in”应用于字符串时,它只查找字符的子字符串。在

尝试:

engSentenceWords = engSentence.split()

后来

^{pr2}$

它将原始句子分割成一个单字列表,然后检查整个单词的值。在

或者更简单,在句子和搜索词中添加空格:

engWords = ["the", "a", "and", "of", "be", "that", "have", "it", "for", "not"]
engSentence = "the dogs fur is black and white"

print("the english sentence is: " + engSentence)

engWords2 = []
isEnglish = 0
engSentence += " "

for w in engWords:
    if "%s " % w in engSentence:
        isEnglish = 1
        engWords2.append(w)

if isEnglish == 1:
    print("The sentence is english and contains the words: ")
    print(engWords2)

输出为:

^{pr2}$

相关问题 更多 >

    热门问题