如何使用Python标记字符串中的单词,取决于它们是在一个特定单词之后还是在句号之前



我有一个字符串列表,其中包含如下工作描述:

direct or coordinate an organization's financial or budget activities to fund operations, maximize investments, or increase efficiency. may serve as liaisons between organizations, shareholders, and outside organizations. may attend and participate in meetings of municipal councils or council committees. represent organizations or promote their objectives at official functions, or delegate representatives to do so.

我已经有了一些python代码,它可以拆分描述中的每个单词,并为其提供一些属性,例如它在描述中出现的次数、位置(根据数字排名(或POS标记(无论是名词还是动词等(;计划时间表";,我的程序已经可以给我以下内容:

[('plan', 'plan', 'NN', 0, 2, 5, 'construction managers', '11-9021.00', 245), ('schedule', 'schedul', 'NN', 1, 1, 1, 'construction managers', '11-9021.00', 245)]

我想添加一个标志/布尔值,对于定义中的每个单词,它都会突出显示单词"may"之后的和单词"full stop"之前的。本质上,我会为每个描述寻找一个布尔值列表,我可以将其压缩到上面的结构中作为第10个属性,并知道每个单词是否介于"may"和句号之间。

关于如何实现这一目标,有什么建议吗?

我假设你想在单词";可以";以及句号,即是否允许某人执行某项任务。

编译完关键字列表后,可以使用正则表达式和re库来搜索匹配的字符串。

如果在字符串中找到正则表达式,则re.search方法返回Match对象,否则返回None。但这两种情况也可以转换为布尔变量:

import re
def may_matcher(string, keyword):
return bool(re.search(r'mays(w*s)*'+keyword+'s*(w*s)*w*.',string))

应用这个小函数可以得到所需的布尔值:

string = "may attend to guests."
may_matcher(string, "attend")
may_matcher(string, "help")

第一行的评估结果为True,而第二行的评估值为False

然后你可以使用列表理解来浏览你的所有关键词:

keywords = ["attend", "help"]
may_list = [may_matcher(string,keyword) for keyword in keywords]

应该注意的是,人们应该小心否定句:;可以不"也会被这个函数匹配!如果这样的句子也存在,您将不得不修改正则表达式。

最新更新