python - 如何将组合的 spacy ner 标签转换为 BIO 格式?
问题描述
如何将其转换为 BIO 格式?我曾尝试使用 spacy biluo_tags_from_offsets
,但它未能捕获所有实体,我想我知道原因。
tags = biluo_tags_from_offsets(doc, annot['entities'])
BSc(理学学士)-这两者结合在一起,但是当有空格时,spacy会拆分文本。所以现在单词会像 ( BSc(Bachelor, of, science
) 这就是 spacybiluo_tags_from_offsets
失败并返回的原因-
现在,当它检查时,(80, 83, 'Degree')
它无法单独找到 BSc 词。同样,它将再次失败(84, 103, 'Degree')
。
我该如何解决这些情况?如果有人可以,请提供帮助。
EDUCATION: · Master of Computer Applications (MCA) from NV, *********, *****. · BSc(Bachelor of science) from NV, *********, *****
{'entities': [(13, 44, 'Degree'), (46, 49, 'Degree'), (80, 83, 'Degree'), (84, 103, 'Degree')]}
解决方案
通常,您将数据传递到biluo_tags_from_offsets(doc, entities)
, where entities
are like [(14, 44, 'ORG'), (51, 54, 'ORG')]
。您可以根据需要编辑此参数(您也可以从编辑开始doc.ents
并从那里继续)。您可以添加、删除、组合此列表中的任何实体,如下例所示:
import spacy
from spacy.gold import biluo_tags_from_offsets
nlp = spacy.load("en_core_web_md")
text = "I have a BSc (Bachelors of Computer Sciences) from NYU"
doc = nlp(text)
print("Entities before adding new entity:", doc.ents)
entities = []
for ent in doc.ents:
entities.append((ent.start_char, ent.end_char, ent.label_))
print("BILUO before adding new entity:", biluo_tags_from_offsets(doc, entities))
entities.append((9,12,'ORG')) # add a desired entity
print("BILUO after adding new entity:", biluo_tags_from_offsets(doc, entities))
Entities before adding new entity: (Bachelors of Computer Sciences, NYU)
BILUO before adding new entity: ['O', 'O', 'O', 'O', 'O', 'B-ORG', 'I-ORG', 'I-ORG', 'L-ORG', 'O', 'O', 'U-ORG']
BILUO after adding new entity: ['O', 'O', 'O', 'U-ORG', 'O', 'B-ORG', 'I-ORG', 'I-ORG', 'L-ORG', 'O', 'O', 'U-ORG']
如果您希望合并实体的过程基于规则,您可以使用以下简化示例尝试entityruler(取自上面的链接):
from spacy.lang.en import English
from spacy.pipeline import EntityRuler
nlp = English()
ruler = EntityRuler(nlp)
patterns = [{"label": "ORG", "pattern": "Apple"},
{"label": "GPE", "pattern": [{"LOWER": "san"}, {"LOWER": "francisco"}]}]
ruler.add_patterns(patterns)
nlp.add_pipe(ruler)
doc = nlp("Apple is opening its first big office in San Francisco.")
print([(ent.text, ent.label_) for ent in doc.ents])
然后再次将重新定义(在您的情况下合并)实体的列表传递给biluo_tags_from_offsets
,就像在第一个代码片段中一样
推荐阅读
- microservices - 使用微服务和网关进行身份验证和授权
- neo4j - Neo4j:强制节点唯一性,一对一匹配
- javascript - 为什么我的数组的顺序在 for 循环中保持变化
- websocket - 为什么 kdb 将 0N 0N 0N 0Ni 显示为 websocket 响应
- java - 难以将 Maven Apache 添加到系统 PATH
- python-3.x - 我正在尝试生成数据集,但出现值错误“ValueError:'a' 不能为空,除非没有采样”
- python - 使用python将解析的csv文件上传到DyanmoDB时如何使关键元素与模式匹配
- c# - Azure Function 2.x 如何访问 stable_sid?
- npm - 当 npm audit 什么都不做时,如何使用 react-scripts v2.1.5 修复 npm 包大括号问题?
- c - 使用 malloc 声明变量如何导致丢失位?