python - 在句子中搜索单词
问题描述
我想要一个 Python 函数,它可以从输入的句子和关键字列表中获取关键字。该函数将遍历关键字列表并在句子中搜索给定的关键字。如果句子中有关键字,该函数将返回该关键字。否则它将返回无。
例如,我有一个列表 ["ai", "Machine Learning", "Computer Science"] 和一个句子“我的专业是计算机科学,我目前在一家商店担任零售商”。如果函数实现正确,它将输出关键字Computer Science。但是,目前,由于我使用的是 Python IN ,因此我的函数正在输出Computer Science和ai(零售商也有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)
解决方案
我认为你最好的方法是使用正则表达式,因为如果你只是使用in
,它会匹配,因为ai
is in the word retailer
。\b
您可以在正则表达式 ( )中使用单词边界。
>>> import re
>>> keywords = "|".join(keywords_list)
>>> re.findall(f"\\b({keywords})\\b", sentence)
['Computer Science']
推荐阅读
- reactjs - 如何知道什么改变了 React State
- sql - 如何在一条 SQL 语句中组合两个不同的 SQL 查询?
- r - 创建每月吸收率图
- excel - 如何使用单个公式计算条件中位数数组的平均值?
- javascript - 根据数据库变量生成“n”个 html 输入
- c# - 从 Datagridviewcells 更新 Oracle 表
- r - 提取多边形质心的坐标并按多边形编号对其进行标记
- javascript - 如何在 a 中左右浮动元素标签?
- javascript - ForEach 中的 setTimeout 不会等待给定的特定毫秒
- string - 带有三元运算符的 Java SE 11 字符串最终变量在 Switch Case 表达式中不计为常量变量