首页 > 解决方案 > 在句子中搜索单词

问题描述

我想要一个 Python 函数,它可以从输入的句子和关键字列表中获取关键字。该函数将遍历关键字列表并在句子中搜索给定的关键字。如果句子中有关键字,该函数将返回该关键字。否则它将返回无。

例如,我有一个列表 ["ai", "Machine Learning", "Computer Science"] 和一个句子“我的专业是计算机科学,我目前在一家商店担任零售商”。如果函数实现正确,它将输出关键字Computer Science。但是,目前,由于我使用的是 Python IN ,因此我的函数正在输出Computer Scienceai零售商也有ai ) 。有什么方法可以改善我的功能以获得更合适的结果?

这是我尝试的代码:

sentence = "My major is Computer Science, and I am currently working as a retailer for a store"

keywords_list = ["ai", "Machine Learning", "Computer Science"]

output_list = list()

for keyword in keywords_list:
    if keyword in sentence:
        output_list.append(keyword)

标签: pythonregex

解决方案


我认为你最好的方法是使用正则表达式,因为如果你只是使用in,它会匹配,因为aiis in the word retailer\b您可以在正则表达式 ( )中使用单词边界。

>>> import re
>>> keywords = "|".join(keywords_list)
>>> re.findall(f"\\b({keywords})\\b", sentence)
['Computer Science']

推荐阅读