【问题标题】:Remove Named Entities from the spacy object从 spacy 对象中删除命名实体
【发布时间】:2020-03-04 11:46:27
【问题描述】:

我正在尝试使用 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 对象被标记化了。因此,我无法使用上面的代码删除 NE。关于如何从对象中删除所有命名实体的任何想法?

【问题讨论】:

    标签: python nlp spacy named-entity-recognition


    【解决方案1】:

    你要检查的条件是

    if item.ent_type:
    

    如果item(“令牌”)是命名实体的一部分,则计算结果为Truetoken.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后面是否跟空格。

    有关详细信息,请参阅Tokenhere 上的文档。

    仅供参考 - 对于未来,包含工作的最小 sn-p 代码会更方便,而不仅仅是部分代码。

    【讨论】:

    • 太棒了!非常感谢!是的,很抱歉没有最小的 sn-p。我的文字非常庞大。我不知道如何正确包含它。
    猜你喜欢
    • 2020-04-06
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 2021-02-23
    • 1970-01-01
    相关资源
    最近更新 更多