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

如何从pandas DataFrame行内嵌套字典提取allennlp OIE目标值并关联原句ID

Allennlp开放信息抽取结果关联原句ID的实现方案

现状梳理

  • 已基于Allennlp OIE预测器实现开放信息抽取功能,可从输入文本中提取以ARG0、V、ARG1等形式标注的主语、谓语、宾语类信息,核心需求是保证每一条输出的抽取结果都能匹配到原句对应的唯一ID
  • 目前生成的DataFrame包含sentence、ID、OIE output三列,其中OIE output列存储预测器返回的原始嵌套结构:
    • 第1行对应内容:句子为'The girl went to the cinema'、关联ID为'abcd',原始OIE输出为{'verbs':[{'verb': 'went', 'description':'[ARG0: The girl] [V: went] [ARG1:to the cinema]'}]}
    • 第2行对应内容:句子为'He is right and he is an engineer'、关联ID为'efgh',原始OIE输出为{'verbs':[{'verb': 'is', 'description':'[ARG0: He] [V: is] [ARG1:right]'}, {'verb': 'is', 'description':'[ARG0: He] [V: is] [ARG1:an engineer]'}]}
  • 生成当前DataFrame的核心代码如下:
oie_l = []
for sent in sentences:
  oie_pred = predictor_oie.predict(sentence=sent) #allennlp oie predictor
  for d in oie_pred['verbs']: #遍历嵌套结构
    d.pop('tags') #移除不需要的tags字段
  oie_l.append(oie_pred)

df['OIE out'] = oie_l #将OIE结果新增为DataFrame列

预期输出效果

最终目标输出表保留sentence、ID、OIE Triples三列,单条抽取到的三元组单独占一行,自动关联对应原句的内容和ID:

  • 第1行:句子为'The girl went to the cinema'、ID为'abcd',OIE Triples值为'[ARG0: The girl] [V: went] [ARG1:to the cinema]'
  • 第2行:句子为'He is right and he is an engineer'、ID为'efgh',OIE Triples值为'[ARG0: He] [V: is] [ARG1:right]'
  • 第3行:句子为'He is right and he is an engineer'、ID为'efgh',OIE Triples值为'[ARG0: He] [V: is] [ARG1:an engineer]'

方案选型与实现

两种初步思路的对比

  • 思路1:将原始OIE输出转为字符串后用正则表达式提取各类ARG信息:鲁棒性较差,Allennlp返回的description格式、ARG标注类型不是完全固定的,正则规则需要反复适配,维护成本高
  • 思路2:遍历嵌套结构提取所有description值组成列表,再调用df.explode()展开:为最优方案,完全基于Allennlp返回的结构化字段做提取,不需要额外的字符串解析逻辑,展开过程会自动继承原行的sentence、ID字段,匹配准确率高,适配性强

具体实现步骤

在现有代码基础上仅需增加两步操作即可达到目标效果:

# 1. 从原始OIE输出中提取所有description值,组成独立列
df['OIE Triples'] = df['OIE out'].apply(
    lambda oie_res: [item['description'] for item in oie_res['verbs']]
)
# 2. 展开列表列,自动关联原句、ID,移除不需要的原始OIE输出列
result_df = df.explode('OIE Triples', ignore_index=True).drop(columns=['OIE out'])

该实现方案不需要额外处理格式适配问题,哪怕后续OIE输出出现ARG2、ARG_LOC等其他标注类型,只要description字段正常返回,代码即可直接适配,无需修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.24 07:27:03