如何在Python中按句号拆分文本但忽略i.e.、e.g.等缩写中的句号
英文句子拆分忽略缩写内部句号的实现方案
核心实现逻辑
直接通过正则匹配仅作为句子结束标记的句号,既不会修改原文内容,也不会误拆分i.e.、e.g.这类缩写,效率远高于临时替换字符串的方案。
匹配规则如下:
- 排除句号前是
i.e/e.g缩写前缀的情况 - 要求句号后紧跟空格+大写字母(标准英文句子的起始格式)
代码实现
import re def split_sentences(text: str) -> list: # 正则规则:匹配符合句子结束特征的句号 split_pattern = r'(?<!\b[iIeE]\.[gG])\.(?=\s+[A-Z])' # 拆分后补回每个句子末尾的句号 sentences = [s.strip() + '.' for s in re.split(split_pattern, text)] # 移除末尾可能产生的空元素 if sentences and sentences[-1] == '.': sentences.pop() return sentences
测试效果
输入文本
During this time, it became apparent that vanilla shortest-path routing would be insufficient to handle the myriad operational, economic, and political factors involved in routing. ISPs began to modify routing configurations to support routing policies, i.e. goals held by the router’s owner that controlled which routes were chosen and which routes were propagated to neighbors.
输出结果
[ "During this time, it became apparent that vanilla shortest-path routing would be insufficient to handle the myriad operational, economic, and political factors involved in routing.", "ISPs began to modify routing configurations to support routing policies, i.e. goals held by the router’s owner that controlled which routes were chosen and which routes were propagated to neighbors." ]
完全符合预期输出要求。
规则拓展
如果后续需要适配其他带句号的缩写(比如etc.、Mr.、Ms.),只需要修改否定后行断言的规则即可,示例如下:
# 新增适配etc.、Mr.、Ms.的规则 split_pattern = r'(?<!(\b[iIeE]\.[gG]|\betc|\bMr|\bMs))\.(?=\s+[A-Z])'
内容的提问来源于stack exchange,提问作者jx-zh
相关产品推荐
相关产品推荐

