【问题标题】:In spacy if a word is tagged for different entity type then how to remove one entity type and its span?在spacy中,如果一个词被标记为不同的实体类型,那么如何删除一个实体类型及其跨度?
【发布时间】:2021-12-03 15:35:20
【问题描述】:

输入:

[('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')]})]

【问题讨论】:

    标签: python list tuples spacy


    【解决方案1】:

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

    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)
    

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

    【讨论】:

      猜你喜欢
      • 2021-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-19
      相关资源
      最近更新 更多