首页 > 解决方案 > 检查一个句子是否连续包含多个单词(Python)

问题描述

我想编写一个函数来检查给定的句子是否包含给定的单词。例如:

my_string = 'Biden'
sentence = 'Biden is the new president of the United States.'

if my_string.lower() in sentence.lower().split():
    print('Sentence contains string')
else:
    print('Sentence does not contain string')

此示例将返回 True。现在,一旦字符串不仅仅是一个单词,就会出现问题。

my_string = 'Joe Biden'
sentence = 'Joe Biden is the new president of the United States.'

if my_string.lower() in sentence.lower().split():
    print('Sentence contains string')
else:
    print('Sentence does not contain string')

在这里它将返回 False。这个问题有简单的解决方案吗?

标签: pythoncontainswordsentence

解决方案


You could use a regular expression - the thing you're looking for encapsulated by word-boundaries:

import re

word = "Joe Biden"
pattern = f"\\b{word}\\b"

sentence = "Joe Biden is the new president of the United States"
match = re.search(pattern, sentence, re.IGNORECASE)

print(f"Sentence {('contains', 'does not contain')[match is None]} string")

推荐阅读