【问题标题】:Add known matches to Spacy document with character offsets使用字符偏移将已知匹配添加到 Spacy 文档
【发布时间】:2021-09-30 13:55:44
【问题描述】:

我想使用不同的 Spacy 工具对文档进行一些分析,但我对依赖匹配器特别感兴趣。

碰巧对于这些文档,我已经有了一些难以解析的实体的字符偏移量。一个有点做作的例子:

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 docs 没有显示类似的内容。我也理解这可能与典型的 Matcher 行为有点不同,其中一个模式可以应用于语料库中的所有文档——而在这里我只想为特定文档标记特定偏移量的实体。一个文档的偏移量不适用于其他文档。

【问题讨论】:

    标签: python machine-learning nlp spacy dependency-parsing


    【解决方案1】:

    您正在寻找Doc.char_span

    doc = "Blah blah blah"
    span = doc.char_span(0, 4, label="BLAH")
    doc.ents = [span]
    

    请注意,doc.ents 是一个元组,因此您不能附加到它,但您可以将其转换为列表并设置 ents,例如。

    【讨论】:

    • 我最终在Spacy guides 中找到了类似的说明,并来到这里发布解决方案,但这一个也很好。不知道为什么它被否决了,因为它完全按照需要工作。
    • 也许“blah blah blah”似乎轻率?不知道,很高兴它有所帮助!
    猜你喜欢
    • 2021-01-04
    • 2012-08-08
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多