命名实体识别与 spacy

时间:2021-02-02 11:11:40

标签: python nlp spacy

我正在使用 python 中的 spacy 库进行自然语言处理。 从输入我得到几个句子,我使用这个单独工作

for sent in doc.sents:

对于每个发送的我使用 .ents 属性搜索任何命名实体。 我想要实现的是用一个新的替换初始的“发送”,其中每个被识别的命名实体都被替换在初始句子上。 举个例子:

First sentence: Apple is looking at buying U.K. startup for $1 billion
After replacing: ORG is looking at buying GPE startup for MONEY

当然使用简单的 string.replace 不起作用,因为我想要一个新的 spacy.Doc 知道如何实现这一目标吗?

1 个答案:

答案 0 :(得分:1)

您不妨试试:

import spacy

nlp = spacy.load("en_core_web_md")   
in_ = "Apple is looking at buying U.K. startup for $1 billion"
doc = nlp(in_)
out = []
for sent in doc.sents:
    sent_out = ""
    for tok in sent:
        ws = " " if tok.whitespace_ else ""
        if tok.ent_type_:
            sent_out += tok.ent_type_ + ws
        else:
            sent_out += tok.text + ws
    out.append(sent_out)
    
print(out)

['ORG is looking at buying GPE startup for MONEYMONEY MONEY']

注意一个特殊的模式 MONEYMONEY MONEY,其中有 3 个实体:其中 2 个没有用空格分隔,1 个被分隔。