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

Python正则提取含关键词句子:忽略日期与特定缩写句号及报错修复

提取包含指定关键词的句子(忽略特定句号)

问题需求

需要从文本中搜索关键词并提取包含该关键词的完整句子,提取时需忽略以下场景中的句号:

  • 日期中的句号(如01.02.2024)
  • 特定缩写后的句号(st.和numb.)

示例

  • 关键词:grand
  • 输入文本:

"The boy will visit his grandmother tomorrow, on 01.02.2024, who lives on Downing St. 10. The following day he will go to school. The day after, on 03.02.2014, he will visit his grandfather."

  • 预期结果:
["The boy will visit his grandmother tomorrow, on 01.02.2024, who lives on Downing St. 10.", "The day after, on 03.02.2014, he will visit his grandfather." ]

原正则报错分析

原使用的正则表达式触发错误:错误信息:后向断言要求固定宽度的模式

out = re.findall('[.](([a-zяA-Z ,:;-])|((([0-9]{1,2}[./]){0,1}([0-9]{1,2}[./]){0,1}([0-9]{2,4}))))*'+keyword+'\w+\W+([a-zA-Z ,:;-]|(([0-9]{1,2}[./]){0,1}([0-9]{1,2}[./]){0,1}([0-9]{2,4})))*(?<!((st)|(numb)))[.]', x)

报错原因:Python的re模块中,后向断言((?<!...))要求匹配的内容是固定宽度的。原正则中(?<!((st)|(numb)))同时匹配2字符的st和4字符的numb,属于可变宽度模式,不符合语法要求。

解决方案

调整后向断言为多个固定宽度的独立断言,同时优化整体匹配逻辑,确保正确识别句子边界:

import re

keyword = "grand"
text = "The boy will visit his grandmother tomorrow, on 01.02.2024, who lives on Downing St. 10. The following day he will go to school. The day after, on 03.02.2014, he will visit his grandfather."

# 编译正则:处理固定宽度后向断言,非贪婪匹配避免跨句
pattern = re.compile(
    r'(?:^|\. )(.*?' + re.escape(keyword) + r'.*?)(?<!st)(?<!numb)\.',
    re.DOTALL
)

# 提取结果并补全末尾句号
result = [match.group(1) + '.' for match in pattern.finditer(text)]
print(result)

正则逻辑说明

  1. (?:^|\. ):匹配句子的起始点,支持文本开头或前一句结束的句号+空格
  2. .*?' + re.escape(keyword) + r'.*?':非贪婪匹配包含关键词的内容,防止跨句子匹配
  3. (?<!st)(?<!numb)\.:用两个独立的固定宽度后向断言,确保句号前不是st或numb,满足语法要求
  4. re.DOTALL:让.匹配换行符,支持多行文本场景

运行结果

输出与预期完全一致:

["The boy will visit his grandmother tomorrow, on 01.02.2024, who lives on Downing St. 10.", "The day after, on 03.02.2014, he will visit his grandfather." ]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 06:42:05