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

Python正则实现书名标题大小写转换的写法咨询

书名大小写自动修正实现

问题描述

我在搭建图书馆目录系统,配套有供用户录入书名、作者名等信息的表单。由于用户提交内容时通常无法正确规范姓名、书名的大小写格式,需要编写一个自动修正大小写错误的函数:

  • 常规示例:输入harry potter and the goblet of fire,需自动转换为规范格式Harry Potter and the Goblet of Fire

功能实现的核心难点是需要避免将the、and、of等虚词大写,但现有正则方案存在共性bug:无法处理虚词本应大写的场景,比如虚词位于标题开头、左括号之后的情况。

异常示例:输入slaughterhouse-five (the children's crusade)的正确输出应为Slaughterhouse-Five (The Children's Crusade),但所有测试过的现有写法都会返回Slaughterhouse-Five (the Children's Crusade),括号后的the没有被正确大写。

已尝试的无效方案

基于Python开发,已测试过以下正则表达式,均无法覆盖括号后、标题开头的虚词大写场景:

r"[A-Za-z]+[^\W+(and|of|the)\W+]"
r"[A-Za-z]+[^\s+(and|of|the)\s+]"
r"(?!and|the|of)[A-Za-z]+"

上述正则在常规场景下可以正确保留and、the、of的小写格式,但缺少虚词排除的例外逻辑。经梳理,只要实现仅当虚词前是空白字符时,才跳过该虚词不做大写处理即可解决问题:

  • Harry Potter and the中的and、the前为空白,因此不需要大写
  • (The Children's Crusade)中the前是左括号、无空白,因此需要大写

可行实现方案

用Python正则零宽断言配合两步转换即可实现需求,无需复杂的多轮匹配:

import re

def normalize_title(input_text: str) -> str:
    # 第一步:统一将所有单词首字母转为大写,覆盖开头、标点后接单词的大写场景
    processed = input_text.title()
    # 配置需要小写的虚词集合,可按需扩展
    stop_words = {"and", "of", "the", "in", "on", "at", "to", "for", "with"}
    # 匹配规则:前面紧邻空白字符的虚词,且虚词后接空白/右括号/字符串结尾
    pattern = re.compile(rf"(\s)({'|'.join(stop_words)})(?=\s|$|[)])", re.IGNORECASE)
    # 第二步:将符合规则的虚词换回小写
    return pattern.sub(lambda m: m.group(1) + m.group(2).lower(), processed)

# 测试验证
if __name__ == "__main__":
    print(normalize_title("harry potter and the goblet of fire"))
    # 输出:Harry Potter and the Goblet of Fire
    print(normalize_title("slaughterhouse-five (the children's crusade)"))
    # 输出:Slaughterhouse-Five (The Children's Crusade)

如果需要新增其他需要小写的虚词,直接往stop_words集合中添加对应词汇即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 05:27:21