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

如何为Spacy分词器批量添加特殊缩写规则以优化分句

解决Spacy批量添加缩写分句规则的方案

方法1:通过列表批量添加缩写

先定义所有需要处理的缩写列表,循环遍历后给每个缩写添加特殊分词规则,确保缩写后的句号不会被当作句子分隔符。

修改后的代码:

import spacy
import pathlib
from spacy.attrs import ORTH, NORM

nlp = spacy.load('en_core_web_sm')

# 定义需要处理的缩写列表,可根据需求扩展
abbreviations = [
    ('Mr.', 'Mister'),
    ('Dr.', 'Doctor'),
    ('Ms.', 'Miss'),
    ('Mrs.', 'Mistress'),
    ('Prof.', 'Professor'),
    ('Sr.', 'Senior'),
    ('Jr.', 'Junior')
]

# 批量添加特殊规则
for abbr, full_form in abbreviations:
    nlp.tokenizer.add_special_case(abbr, [{ORTH: abbr, NORM: full_form}])

file_name = r"text_test_sentence.txt"
doc = nlp(pathlib.Path(file_name).read_text(encoding="utf-8"))
sentences = list(doc.sents)

# 测试输出分句结果
for idx, sent in enumerate(sentences):
    print(f"Sentence {idx}: {sent.text}")

方法2:从文本文件批量读取缩写

如果缩写数量极多,可将缩写存入文本文件,再读取后批量处理。

第一步:创建缩写配置文件(比如abbreviations.txt)

每行格式示例:

Mr.|Mister
Dr.|Doctor
Ms.|Miss
Mrs.|Mistress
Prof.|Professor

第二步:读取文件批量添加规则

代码如下:

import spacy
import pathlib
from spacy.attrs import ORTH, NORM

nlp = spacy.load('en_core_web_sm')

# 读取缩写配置文件
abbr_file = pathlib.Path("abbreviations.txt")
abbreviations = []
with open(abbr_file, 'r', encoding='utf-8') as f:
    for line in f:
        line = line.strip()
        if line:
            abbr, full_form = line.split('|')
            abbreviations.append((abbr.strip(), full_form.strip()))

# 批量添加特殊规则
for abbr, full_form in abbreviations:
    nlp.tokenizer.add_special_case(abbr, [{ORTH: abbr, NORM: full_form}])

file_name = r"text_test_sentence.txt"
doc = nlp(pathlib.Path(file_name).read_text(encoding="utf-8"))
sentences = list(doc.sents)

# 测试输出分句结果
for idx, sent in enumerate(sentences):
    print(f"Sentence {idx}: {sent.text}")

关键说明

  • 特殊规则的核心是让Spacy将整个缩写(如Dr.)识别为单个token,避免把缩写后的句号当作句子结束标记,从而防止错误分句。
  • 如果你不需要统一缩写的标准化形式(NORM字段),可以简化规则为[{ORTH: abbr}],只保留原拼写的分词规则即可。
  • 若仍存在部分分句错误,可检查是否有遗漏的缩写,补充到列表或配置文件中即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 19:22:58