首页 > 解决方案 > 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...来实现这一点?

标签: pythonentityspacynamed-entity-recognition

解决方案


我建议使用以下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


推荐阅读