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,或者不适用于短语

这件事检查子字符串,所以任何正确的字符序列,无论它们是否在单词的中间。

您需要的是regex搜索-regex有一个特殊的字符来表示"单词边界"-b:

import re
for item in listA:
if re.search(r"b{}b".format(item), sentence.lower().strip()):
print('success')
else:
print('Not Present')

在单词的前面和末尾添加空格,然后使用您使用过的相同代码进行检查。

for item in listA:
if ' '+item+' ' in sentence.lower():
print('success')
else:
print('Not Present')

最新更新