首页 > 解决方案 > 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或不适用于短语

标签: pythonregex

解决方案


这个东西检查一个子字符串,所以任何正确的字符序列,不管它们是否在单词的中间。

您需要的是正则表达式搜索 - 正则表达式有一个特殊字符来表示“单词边界” - \b

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

推荐阅读