Spacy - 区块 NE 代币

Spacy - Chunk NE tokens

假设我有一个文件,像这样:

import spacy

nlp = spacy.load('en')

doc = nlp('My name is John Smith')

[t for t in doc]
> [My, name, is, John, Smith]

Spacy 足够聪明,可以意识到 'John Smith' 是一个多标记命名实体:

[e for e in doc.ents]
> [John Smith]

如何将命名实体分块成离散的标记,如下所示:

> [My, name, is, John Smith]

NER 上的 Spacy 文档说您可以使用 token.ent_iob_token.ent_type_ 属性访问令牌实体注释。

https://spacy.io/usage/linguistic-features#accessing

示例:

import spacy

nlp = spacy.load('en')
doc = nlp('My name is John Smith')


ne = []
merged = []
for t in doc:
    # "O" -> current token is not part of the NE
    if t.ent_iob_ == "O":
        if len(ne) > 0:
            merged.append(" ".join(ne))
            ne = []
        merged.append(t.text)
    else:
        ne.append(t.text)

if len(ne) > 0:
    merged.append(" ".join(ne))

print(merged)

这将打印:

['My', 'name', 'is', 'John Smith']