我想使用不同的Spacy工具对文档进行一些分析,尤其是对Dependency Matcher感兴趣。
恰好,对于这些文档,我已经知道了一些难以解析的实体的字符偏移量。一个稍微有些编造的例子:
from spacy.lang.en import Englishnlp = 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"}]# 在这里做一些操作,让`nlp`知道这些实体 doc = nlp(text)
我考虑过这样做:
from spacy.lang.en import Englishnlp = 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"}]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文档并没有显示这样的内容。我也理解这可能与典型的Matcher行为有所不同,在典型的Matcher行为中,一个模式可以应用于语料库中的所有文档——而在这里,我希望仅为特定文档标记特定偏移量的实体。一个文档的偏移量不适用于其他文档。
回答:
你正在寻找Doc.char_span。
doc = "Blah blah blah"span = doc.char_span(0, 4, label="BLAH")doc.ents = [span]
请注意,doc.ents
是一个元组,所以你不能直接向它添加内容,但你可以将其转换为列表并设置ents,例如。