python - 在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')]})]
解决方案
如果您尝试分配一个冲突的注释,您将得到一个异常,因此您可以使用此代码仅保留第一个注释。如果您想保留第二个注释,则必须弄清楚如何按优先级顺序分配它们,您没有解释您如何知道您想要第二个注释,所以我将把它留给您。
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)
请注意,这不适用于您提供的示例数据,因为您的所有字符偏移都已关闭,因此无法获得有效的跨度。
推荐阅读
- javascript - 如何让屏幕阅读器在 Angular 或任何单页应用程序中加载新页面时通知?
- python - python 3.7单行理解
- javascript - React - useState 仅影响最后一个属性值
- sql - 检查 postgres 表中列的唯一性
- c++ - 如何在内存中的数据缓冲区上使用常规 std::basic_istream::read、std::basic_ostream::write?
- linux - 如何使用 bash 同时运行多个可执行代码?
- java - 创建基于自定义生成器/迭代器方法的流
- virtual - Vmware 工作站 15 上的 RDP
- amazon-web-services - AWS Cloudformation:“Lambda 函数的权限无效”出了什么问题?
- python - Numpy 按中位数分组(没有 Pandas)