首页 > 解决方案 > 在spacy中,如果一个词被标记为不同的实体类型,那么如何删除一个实体类型及其跨度?

问题描述

输入:

[('PERSON1: thank you for calling ABCD my name is QWERT and him i speaking with PERSON2: hi QWERT this is QAZWSXE RFVTGB', {'entities': [(102, 116, 'PERSON'), (29, 33, 'ORG'), (45, 50, 'PERSON'), (45, 50, 'ORG')]})]

在这里,假设“QWERT”被标记为 (45, 50, 'PERSON') 和 (45, 50, 'ORG') 所以我们需要删除第二个实体类型及其跨度 (45, 50, 'ORG') 注意:在这个例子中,我们有 4 种实体类型和它们的跨度,但这个数字会有所不同

预期结果:

[('PERSON1: thank you for calling ABCD my name is QWERT and him i speaking with PERSON2: hi QWERT this is QAZWSXE RFVTGB', {'entities': [(102, 116, 'PERSON'), (29, 33, 'ORG'), (45, 50, 'PERSON')]})]

标签: pythonlisttuplesspacy

解决方案


如果您尝试分配一个冲突的注释,您将得到一个异常,因此您可以使用此代码仅保留第一个注释。如果您想保留第二个注释,则必须弄清楚如何按优先级顺序分配它们,您没有解释您如何知道您想要第二个注释,所以我将把它留给您。

import spacy
nlp = spacy.blank("en")

# put your data here
data = ...
cleaned = []

for text, annotations in data:
    ents = annotations["entities"]
    doc = nlp(text)
    for start, end, label in ents:
        try:
            span = doc.char_span(start, end, label=label)
            if span:
                doc.ents = doc.ents + (span,)
        except:
            # if it overlaps we'll get an exception
            print("skipping:", start, end, label)
    out_ents = [(ss.start, ss.end, ss.label) for ss in doc.ents]
    cleaned.append( (text, {"entities": out_ents}) )

print(cleaned)

请注意,这不适用于您提供的示例数据,因为您的所有字符偏移都已关闭,因此无法获得有效的跨度。


推荐阅读