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

使用Stanza提取时间日期实体时如何获取其前后关联上下文内容

解答

不需要额外编写正则代码,直接使用Stanza本身返回的实体位置、句子结构信息就能实现需求,两种常用实现方案如下:

  • 方案1:提取时间实体所属的完整句子
    适合需要完整动作上下文的场景,Stanza识别出的每个实体都绑定了所属的句子对象,直接获取对应句子的全文即可,改后代码示例:
    def show_time_ents_with_sentence(doc):
        entities = []
        if not doc.entities:
            print('No named entities found.')
            return entities
        for entity in doc.entities:
            if entity.type in ('TIME', 'DATE'):
                # 获取实体所属的完整句子
                belong_sent = entity.sent.text
                print(f"时间实体:{entity.text},所属上下文:{belong_sent}")
                entities.append(f"{entity.text}:{entity.type} | 上下文:{belong_sent}")
        return entities
    
  • 方案2:提取实体前后指定数量的紧邻关联词
    适合只需要和时间直接绑定的动作短语的场景,每个实体都有start_token和end_token属性,标记了实体在句子token序列里的起始和结束索引,直接按索引取前后指定数量的token拼接即可,比如要实现你示例中的效果,往前取3个词、往后取1个词即可,代码示例:
    def show_time_ents_with_nearby_words(doc, pre_word_num=3, post_word_num=1):
        entities = []
        if not doc.entities:
            print('No named entities found.')
            return entities
        for entity in doc.entities:
            if entity.type in ('TIME', 'DATE'):
                sent = entity.sent
                # 计算要取的token范围,避免索引越界
                start_idx = max(0, entity.start_token - pre_word_num)
                end_idx = min(len(sent.words), entity.end_token + post_word_num)
                # 拼接选中的token文本
                context_text = ' '.join([word.text for word in sent.words[start_idx:end_idx]])
                print(f"时间实体:{entity.text},紧邻上下文:{context_text}")
                entities.append(f"{entity.text}:{entity.type} | 紧邻上下文:{context_text}")
        return entities
    
    用你给出的示例文本测试,该函数可以直接输出watched a movie at 3:00PM on Thursday、ate pancakes at 9:00AM这类符合预期的结果。

如果需要更精准的只提取时间关联的动作核心,还可以结合Stanza的依存句法分析结果,找到时间实体修饰的谓语核心词,再提取对应谓语短语即可,准确率远高于正则匹配,不需要适配复杂的时间表达格式规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:15:03