我正在使用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...
才能实现?
答案 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'])