You need to enable JavaScript to run this app. 如何实现全场景兼容的语句到蛇形命名(snake-case)转换?
优惠活动
大模型
产品
解决方案
定价
更多

如何实现全场景兼容的语句到蛇形命名(snake-case)转换?

全场景适配的语句到蛇形命名(snake-case)转换实现
  • 试过多种单一转换方案,均无法覆盖所有输入场景,因此整合不同方案的优势,写出通用转换逻辑如下:
import re

def to_snake(camel_input):
    # 替换&为语义等价的_and_,匹配财务类常用的p&l等缩写场景
    camel_input = camel_input.replace('&', '_and_')
    # 在非字符串开头位置的大写字母前插入下划线,统一转换为小写
    camel_input = re.sub(r'(?<!^)(?=[A-Z])', '_', camel_input).lower()
    # 按规则拆分所有有效单词片段:普通混合大小写单词、连续大写缩写、纯数字串
    words = re.findall(r'[A-Z]?[a-z]+|[A-Z]{2,}(?=[A-Z][a-z]|\d|\W|$)|\d+', camel_input)
    # 用下划线拼接所有拆分后的片段,得到最终蛇形命名
    return '_'.join(words)
  • 效果验证:选取覆盖多类输入形态的测试串执行转换
    • 测试输入:'my p&l AndP&L aa_BB_dd (teSt) AndMy P&L andAlsoP&L andAlso p&l A B aA'
    • 调用方式:print(to_snake('my p&l AndP&L aa_BB_dd (teSt) AndMy P&L andAlsoP&L andAlso p&l A B aA'))
    • 转换输出结果:
my_p_and_l_and_p_and_l_aa_b_b_dd_te_st_and_my_p_and_l_and_also_p_and_l_and_also_p_and_l_a_b_a_a

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.09 10:15:04