Spacy-块NE令牌

时间:2018-08-11 18:35:19

标签: python tokenize spacy named-entity-recognition

假设我有一个文档,如下所示:

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]

1 个答案:

答案 0 :(得分:1)

有关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']