添加已知匹配到空格文档与字符偏移量



我想使用不同的space工具对文档进行一些分析,尽管我对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,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是一个元组,所以你不能对它进行追加,但是你可以将它转换成一个列表并设置元素,例如

最新更新