python - spaCy - 按标签对实体进行排序的最有效方法
问题描述
我正在使用 spaCy 管道从文章中提取所有实体。我需要将这些实体保存在一个变量上,具体取决于它们被标记的标签。现在我有这个解决方案,但我认为这不是最合适的,因为我需要遍历每个标签的所有实体:
nlp = spacy.load("es_core_news_md")
text = # I upload my text here
doc = nlp(text)
personEntities = list(set([e.text for e in doc.ents if e.label_ == "PER"]))
locationEntities = list(set([e.text for e in doc.ents if e.label_ == "LOC"]))
organizationEntities = list(set([e.text for e in doc.ents if e.label_ == "ORG"]))
spaCy 中是否有直接的方法来获取每个标签的所有实体,或者我需要做些什么for ent in ents: if... elif... elif...
来实现这一点?
解决方案
我建议使用以下groupby
方法itertools
:
from itertools import *
#...
entities = {key: list(g) for key, g in groupby(sorted(doc.ents, key=lambda x: x.label_), lambda x: x.label_)}
或者,如果您只需要提取唯一值:
entities = {key: list(set(map(lambda x: str(x), g))) for key, g in groupby(sorted(doc.ents, key=lambda x: x.label_), lambda x: x.label_)}
然后,您可以使用打印已知实体
print(entities['ORG'])
如果您需要获得实体对象的唯一出现,而不仅仅是字符串,您可以使用
import spacy
from itertools import *
nlp = spacy.load("en_core_web_sm")
s = "Hello, Mr. Wood! We are in New York. Mrs. Winston is not coming, John hasn't sent her any invite. They will meet in California next time. General Motors and Toyota are companies."
doc = nlp(s * 2)
entities = dict()
for key, g in groupby(sorted(doc.ents, key=lambda x: x.label_), lambda x: x.label_):
seen = set()
l = []
for ent in list(g):
if ent.text not in seen:
seen.add(ent.text)
l.append(ent)
entities[key] = l
输出在print(entities['GPE'][0].text)
这里New York
。
推荐阅读
- sorting - BIM360 问题 SortBy()
- dart - 如何从 http 响应中迭代 cookie 值?
- javascript - 如何使用 JavaScript 选择选项?
- c# - 使用服务器对象模型和 caml 查询在共享点列表中创建搜索栏
- c# - 这是 C# SqlDecimal 数学错误吗?
- javascript - 通过键名从对象数组中删除重复对象
- oracle - Oracle 物化视图中的数据何时真正改变?
- jfreechart - 具有相同项目的堆叠条在一行中重复
- xmlunit - XMLUnit 忽略链接中的版本差异
- c++ - 在 C++ 应用程序中使用 C 函数时代码覆盖率 (gcov) 失败