使用spaCy用BIO方案注释文本

时间:2019-02-25 16:57:17

标签: python annotations spacy

我需要使用基于规则方法的BIO方案注释文本语料库(我有一个预定义的标记及其标签列表)。我正在为此任务使用spaCy的EntityRuler类。我的问题是,是否有一种简洁有效的方法来使用spaCy实施BIO标签?另外,我也在努力实现多令牌BIO标记:

 'He used sodium-bicarb 5 gr' -> 
['O', 'O', 'B-DRUG', 'I-DRUG', 'I-DRUG', 'B-STRENGTH', 'I-STRENGTH')

我有一个简单的(基于规则)脚本来标记我感兴趣的实体:

import numpy as np
import pandas as pd
import spacy
from spacy.pipeline import EntityRuler

nlp = spacy.load('en')
ruler = EntityRuler(nlp).from_disk('drug_patterns.jsonl')
nlp.add_pipe(ruler, before='ner')


text = 'He has been prescribed ipratropium-albuterol a small dose of 20mg, denzapine and amil-co'
doc = nlp(text)

for ent in doc.ents:
    print(ent.text, ent.start_char, ent.end_char, ent.label_)

输出:

ipratropium 23 34 DRUG
20mg 61 65 STRENGTH
denzapine 67 76 DRUG
amil-co 81 88 DRUG

因此,我不确定如何将'amil-co'分成三个标签'B-DRUG, I-DRUG and I-DRUG'

理想情况下,我想添加以下注释:

    token          BIO
0   He             O
1   has            O
2   been           O
3   prescribed     O
4   ipratropium    B-DRUG
5   -              I-DRUG
6   albuterol      I-DRUG
7   a              O
8   small          O
9   dose           O
10  of             O
11  20             B-STRENGTH
12  mg             I-STRENGTH
13  ,              O
14  denzapine      B-DRUG
15  and            O
16  amil           B-DRUG
17  -              I-DRUG
18  co             I-DRUG
19  .              O

,在我的词汇表drug_patterns.json中,相同的长标记可能会出现一次,而不是出现一次:

{"label": "DRUG", "pattern": [{"lower": "ipratropium"}]}
{"label": "DRUG", "pattern": [{"lower": "ipratropium"}, {"lower": "bromide"}]}
{"label": "DRUG", "pattern": [{"lower": "ipratropium"}, {"lower": "-"}, {"lower": "albuterol"}]}

,而不是整个ipratropium-albuterol只会选择第一个(最短的)令牌ipratropium(如输出所示)。是否有一种简单的方法告诉spaCy选择最长的令牌?

任何想法都会受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

嗯,这是一个令人尴尬的简单解决方案,但希望它对其他人可能很有趣。只需使用令牌的.ent_iob_.ent_type_属性即可。即:

pd.DataFrame([(e.text, e.ent_iob_, e.ent_type_) for e in doc])


    0   1   2
0   He  O   
1   has O   
2   been    O   
3   prescribed  O   
4   ipratropium B   DRUG
5   -   O   
6   albuterol   O   
7   a   O   
8   small   O   
9   dose    O   
10  of  O   
11  20  B   STRENGTH
12  mg  I   STRENGTH
13  ,   O   
14  denzapine   B   DRUG
15  and O   
16  amil    B   DRUG
17  -   I   DRUG
18  co  I   DRUG
19  .   O   

,然后可以轻松地将后两列以适当的格式与连字符合并。 SpaCy很棒!