python - 检查一个句子是否连续包含多个单词(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。这个问题有简单的解决方案吗?
解决方案
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")
推荐阅读
- node.js - AWS Api Gateway 响应映射正则表达式不起作用
- android - 当 listitem 刚刚可见时,recyclerview 中的 Videoview 开始播放
- html - 我的 HTML / CSS 网站末尾的空白
- python - 如何将列表元素用于 Lamba 循环?
- azure - 如何将内容信任策略分配给容器注册表资源 azure powershell
- mysql - SQL查询获取两个数字之间的数据
- vue.js - 为什么我得到“找不到模块”我已经尝试了很多解决方案
- arrays - 如果接口值不匹配,我们可以将响应数据绑定到 Angular 视图吗?
- r - 如何使用 ggplot2 自定义点图图例的内容
- asynchronous - 异步对象未向 get_it 注册