You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NegSpacy中获取被否定词汇对应的否定术语?

解决方案:修改NegSpacy获取对应否定术语

1. 解决扩展属性未注册的错误

Spacy的自定义扩展属性必须先注册才能赋值,你遇到的AttributeError: [E047]就是因为未注册negate_term属性。

注册扩展属性

在NegSpacy源码的negation.py文件开头添加以下代码:

from spacy.tokens import Span
# 注册扩展属性,default设为None,force=True避免重复注册报错
Span.set_extension("negate_term", default=None, force=True)

2. 修改NegSpacy的否定检测逻辑,关联否定术语

找到negation.py中Negex类的__call__方法,修改实体否定状态判断的代码,同时记录对应的否定术语:

原逻辑(仅设置否定状态):

for e in doc.ents:
    e._.negex = any(neg.start <= e.start and neg.end >= e.end for neg in negations)

修改后的逻辑(同时记录否定术语):

for e in doc.ents:
    matched_neg_term = None
    # 遍历所有否定词范围,找到匹配当前实体的否定词
    for neg in negations:
        if neg.start <= e.start and neg.end >= e.end:
            matched_neg_term = neg.text
            break
    e._.negex = matched_neg_term is not None
    e._.negate_term = matched_neg_term

这段代码会遍历检测到的所有否定词区间,找到覆盖当前实体的否定词,将其文本赋值给e._.negate_term,同时设置negex状态。

3. 安装修改后的NegSpacy

在你克隆的NegSpacy仓库目录下,执行以下命令安装修改后的版本:

pip install -e .

4. 使用示例

运行以下代码即可得到期望的映射关系:

import spacy
from negspacy.negation import Negex

nlp = spacy.load("en_core_sci_lg")
nlp.add_pipe("negex")

doc = nlp("She has neither fever nor cough.")

# 整理输出格式
output = []
for ent in doc.ents:
    if ent._.negex:
        output.append({
            "negated lexicon": ent.text,
            "corresponding negated term": ent._.negate_term
        })

print(output)

输出结果

[
    {"negated lexicon": "fever", "corresponding negated term": "neither"},
    {"negated lexicon": "cough", "corresponding negated term": "nor"}
]

优势说明

  • 基于NegSpacy原有的否定检测逻辑,无需额外自定义匹配规则,覆盖范围广、效率高,适合大规模临床数据集处理;
  • 直接扩展NegSpacy的功能,保持代码的一致性和可维护性。

内容的提问来源于stack exchange,提问作者mehrnoosh azizi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 05:33:33