问题描述
我想使用不同的 Spacy 工具对文档进行一些分析,但我对 Dependency Matcher 特别感兴趣。
碰巧对于这些文档,我已经有了一些难以解析的实体的字符偏移量。一个有点做作的例子:
from spacy.lang.en import English
nlp = English()
text = "Apple is opening its first big office in San Francisco."
already_kNown_entities = [
{"offsets":(0,5),"id": "apple"},{"offsets":(41,54),"id": "san-francisco"}
]
# do something here so that `nlp` kNows about those entities
doc = nlp(text)
我想过做这样的事情:
from spacy.lang.en import English
nlp = English()
text = "Apple is opening its first big office in San Francisco."
already_kNown_entities = [{"offsets":(0,"id": "san-francisco"}]
ruler = nlp.add_pipe("entity_ruler")
patterns = []
for e in already_kNown_entities:
patterns.append({
"label": "GPE","pattern": text[e["offsets"][0]:e["offsets"][1]]
})
ruler.add_patterns(patterns)
doc = nlp(text)
这在技术上是可行的,而且它不是世界上最糟糕的解决方案,但我仍然想知道是否可以直接将偏移添加到 nlp
对象。据我所知,Matcher docs 不会显示这样的内容。我也明白这可能与典型的 Matcher 行为有所不同,在典型的 Matcher 行为中,一种模式可以应用于语料库中的所有文档——而在这里我只想为特定文档标记特定偏移量的实体。一份文件的抵消不适用于其他文件。
解决方法
您正在寻找Doc.char_span。
doc = "Blah blah blah"
span = doc.char_span(0,4,label="BLAH")
doc.ents = [span]
请注意,doc.ents
是一个元组,因此您无法附加到它,但您可以将其转换为列表并设置 ents,例如。