从spacy对象中删除命名实体

3

我正在尝试使用Spacy从文档中删除命名实体。识别命名实体没有遇到任何问题。用了这段代码:

ne = [(ent.text, ent.label_) for ent in doc.ents]
print(ne)
persons = [ent.text for ent in doc.ents if ent.label_ == 'PERSON']
print(persons)

输出:

'Timothy D. Cook',
 'Peter',
 'Peter',
 'Benjamin A. Reitzes',
 'Timothy D. Cook',
 'Steve Milunovich',
 'Steven Mark Milunovich',
 'Peter',
 'Luca Maestri'

但是现在我正在尝试使用这个代码块从文档中删除它们:
text_no_namedentities = []

ents = [e.text for e in doc.ents]
for item in doc:
    if item.text in ents:
        pass
    else:
        text_no_namedentities.append(item.text)
print(" ".join(text_no_namedentities))

它不能工作,因为NE是n-gram。如果我只检查spacy对象的一小块内容,则如下所示:

for item in doc:
    print(item.text)

iPad
has
a
78
%
Steve
Milunovich
share
of
the
U.S.
commercial
tablet
market

因此,Spacy对象已经被标记化。因此,我无法使用上面的代码删除命名实体。有没有办法从对象中删除所有命名实体?

1个回答

3
您想要检查的条件是:

if item.ent_type:

如果“item”(“token”)是命名实体的一部分,则这将评估为True。 token.ent_type将是实体实际类型的哈希ID,您可以使用token.ent_type_查询该类型(请注意下划线)。
我会使用以下代码:
    text_no_namedentities = ""
    for token in doc:
        if not token.ent_type:
            text_no_namedentities += token.text
            if token.whitespace_:
                text_no_namedentities += " "

请注意,您可以使用token.whitespace_来确定原始句子中的原始标记是否后面跟了一个空格。
有关更多信息,请参见此处有关Token的文档here
FYI-将来包含工作的最小代码片段将更加方便,而不仅仅是其中的部分。

太棒了!非常感谢!是的,很抱歉没有提供最小代码片段。我的文本非常庞大。我不知道如何正确地包含它。 - Johnny smith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接