python - Python检查句子中是否存在短语
问题描述
我试图找出列表中的单词/字符串是否存在于给定的句子中。
sentence = 'The total number of cases in germany is equal to the inital cases from china'
listA = []
listA.append('equal to')
listA.append('good')
listA.append('case')
for item in listA:
if item in sentence.lower().strip():
print('success')
else:
print('Not Present')
我也试过
if item in sentence.lower():
和
if item in sentence.lower().split():
但是,这也捕获了短语cases
或不适用于短语
解决方案
这个东西检查一个子字符串,所以任何正确的字符序列,不管它们是否在单词的中间。
您需要的是正则表达式搜索 - 正则表达式有一个特殊字符来表示“单词边界” - \b
:
import re
for item in listA:
if re.search(r"\b{}\b".format(item), sentence.lower().strip()):
print('success')
else:
print('Not Present')
推荐阅读
- python - 在 python 中检查有关 RLE 的逻辑
- reactjs - 如何解决“:react-native-vector-icons”错误以成功构建?
- java - 访问通过 Java Webstart 加载的 JAR 文件
- ios - 使用图像缓存时展开 [String] 的问题
- excel - SOAP UI 写入数据时 Excel 公式未更新
- azure-cosmosdb - 将 Azure Cosmos DB 移动到其他租户
- javascript - 尝试在发生错误时显示注册错误块
- extract - 从语法中提取标记
- node.js - 服务器实例,开玩笑和“听 EADDRINUSE :::3000”
- python-3.x - 如何创建字典组合?最昂贵的汽车问题