如何在CoreNLP中关联遍历token属性与共指消解结果并合并标注数据
CoreNLP共指与token级标注合并方案
核心关联逻辑
两类标注不需要手动做文本匹配,共指链的mention对象自带内置的位置索引属性,可以直接和token级列表一一对应:
- 共指提及
mention的sentenceIndex(0基):对应该提及所属句子在doc.sentence列表中的索引 - 共指提及
mention的tokenStartIndex、tokenEndIndexInclusive(均为0基,后者为包含式结束位置):对应该提及在所属句子的token列表中的起止索引
前置修正
你代码里存在一个笔误:之前赋值的标注结果变量是doc,但遍历token时用了document.sentence,需要统一为doc.sentence否则会报变量未定义错误。
场景1:给每个共指提及关联对应token标注
直接遍历共指链时,通过位置索引提取对应token的pos/lemma/ner信息:
import stanza import os from stanza.server import CoreNLPClient corenlp_dir = '/Users/fatih/stanford-corenlp-4.2.0/' os.environ['CORENLP_HOME'] = corenlp_dir client = CoreNLPClient( annotators=['tokenize','ssplit', 'pos', 'lemma', 'ner', 'coref'], memory='4G', endpoint='http://localhost:9001', be_quiet=True) text = "Barack Obama was born in Hawaii. He is the president. Obama was elected in 2008." doc = client.annotate(text) # 遍历共指链 for coref_chain_idx, coref_chain in enumerate(doc.corefChain): # 同个共指链的提及animacy属性一致 chain_animacy = coref_chain.mention[0].animacy print(f"=== 共指链 {coref_chain_idx} | animacy: {chain_animacy} ===") for mention in coref_chain.mention: # 按位置取出对应句子 target_sent = doc.sentence[mention.sentenceIndex] # 按位置取出对应token范围(Python切片左闭右开,结束索引需+1) start_tok = mention.tokenStartIndex end_tok = mention.tokenEndIndexInclusive mention_tokens = target_sent.token[start_tok : end_tok + 1] # 提取合并后的标注 mention_text = " ".join(t.word for t in mention_tokens) mention_pos = [t.pos for t in mention_tokens] mention_lemma = [t.lemma for t in mention_tokens] mention_ner = [t.ner for t in mention_tokens] # 打印结果 print(f"提及文本:{mention_text}") print(f"位置:第{mention.sentenceIndex+1}句,token[{start_tok+1}, {end_tok+1}]") print(f"标注:lemma={mention_lemma}, pos={mention_pos}, ner={mention_ner}") print("---")
场景2:给每个token补充所属共指属性
预先建立「token位置到共指信息」的映射字典,遍历token时直接查询即可:
# 1. 预先构建token-共指映射 token_coref_map = {} for coref_chain_idx, coref_chain in enumerate(doc.corefChain): chain_animacy = coref_chain.mention[0].animacy for mention in coref_chain.mention: sent_idx = mention.sentenceIndex start_tok = mention.tokenStartIndex end_tok = mention.tokenEndIndexInclusive # 给范围内的每个token赋值共指属性 for tok_idx in range(start_tok, end_tok + 1): token_coref_map[(sent_idx, tok_idx)] = { "coref_chain": coref_chain_idx, "animacy": chain_animacy } # 2. 遍历token时合并打印所有标注 for sent_idx, sent in enumerate(doc.sentence): print(f"[Sentence {sent_idx+1}]") for tok_idx, t in enumerate(sent.token): # 查询当前token的共指信息,无则填默认值 coref_info = token_coref_map.get( (sent_idx, tok_idx), {"coref_chain": "无", "animacy": "无"} ) # 合并所有标注输出 print("{:12s}\t{:12s}\t{:6s}\t{:20s}\t{:10s}\t{}".format( t.word, t.lemma, t.pos, t.ner, f"共指链{coref_info['coref_chain']}", coref_info["animacy"] )) print("")
注意事项
- 所有索引值均为0基,仅需在给人看的打印环节转为1基即可,代码内部直接用原索引对齐
- 不要手动做文本匹配对齐,CoreNLP已经完成了token切分和位置映射,避免因多空格、标点符号导致的匹配错误
内容的提问来源于stack exchange,提问作者Fatih Bozdağ
相关产品推荐
相关产品推荐

