是否有支持英文大小写修正的Python拼写纠错库?
英文小写文本专有名词大小写修正Python解决方案
你可以通过以下两种成熟方案实现需求:
方案1:使用truecase轻量库
这是专门针对仅句首大写、其余内容全小写的文本做大小写校正的工具,内置训练数据已经覆盖常见人名、地名、机构名等专有名词的大小写规则,开箱即用。
- 安装命令:
pip install truecase - 示例代码:
import truecase raw_text = 'And then we went to see frank from england to have a beer with him.' corrected_text = truecase.get_true_case(raw_text) print(corrected_text) # 输出结果:And then we went to see Frank from England to have a beer with him.
方案2:结合spaCy的命名实体识别自定义校正
如果你的文本包含行业专属专有名词,可以用spaCy的NER能力识别实体后自定义大小写规则,灵活度更高。
- 安装依赖:
pip install spacy && python -m spacy download en_core_web_sm - 示例代码:
import spacy nlp = spacy.load("en_core_web_sm") raw_text = 'And then we went to see frank from england to have a beer with him.' doc = nlp(raw_text) corrected_tokens = [] for token in doc: # 识别到人名、地名、组织名实体时,统一首字母大写 if token.ent_type_ in ("PERSON", "GPE", "ORG"): corrected_tokens.append(token.text.capitalize()) else: corrected_tokens.append(token.text) corrected_text = ' '.join(corrected_tokens) print(corrected_text) # 输出结果:And then we went to see Frank from England to have a beer with him.
你可以根据业务场景扩充实体判定规则,适配特殊专有名词的校正需求。
内容的提问来源于stack exchange,提问作者SirNoob
相关产品推荐
相关产品推荐

