spaCy-按标签对实体进行排序的最有效方法

时间:2019-11-27 11:01:48

标签: python entity spacy ner

我正在使用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...才能实现?

1 个答案:

答案 0 :(得分:2)

我建议使用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'])