例子:

>>> convert('CamelCase')
'camel_case'

当前回答

在包索引中有一个inflection库可以为您处理这些事情。在这种情况下,您将寻找inflection.underscore():

>>> inflection.underscore('CamelCase')
'camel_case'

其他回答

下面是我更改制表符分隔的文件头部的一些操作。我省略了只编辑文件第一行的部分。你可以用re库很容易地将它适应Python。这还包括分离数字(但保持数字在一起)。我分两步完成,因为这比告诉它不要在行或制表符的开头放下划线更容易。

第一步……查找大写字母或小写字母前面的整数,并在它们前面加下划线:

搜索:

([a-z]+)([A-Z]|[0-9]+)

替换:

\1_\l\2/

第二步……使用上面的代码并再次运行它,将所有大写字母转换为小写字母:

搜索:

([A-Z])

替换(即反斜杠,小写L,反斜杠,1):

\l\1

以下是我的解决方案:

def un_camel(text):
    """ Converts a CamelCase name into an under_score name. 

        >>> un_camel('CamelCase')
        'camel_case'
        >>> un_camel('getHTTPResponseCode')
        'get_http_response_code'
    """
    result = []
    pos = 0
    while pos < len(text):
        if text[pos].isupper():
            if pos-1 > 0 and text[pos-1].islower() or pos-1 > 0 and \
            pos+1 < len(text) and text[pos+1].islower():
                result.append("_%s" % text[pos].lower())
            else:
                result.append(text[pos].lower())
        else:
            result.append(text[pos])
        pos += 1
    return "".join(result)

它支持评论中讨论的那些极端情况。例如,它会像它应该的那样将getHTTPResponseCode转换为get_http_response_code。

这么多复杂的方法…… 只需找到所有“标题”组,并加入其小写变体与下划线。

>>> import re
>>> def camel_to_snake(string):
...     groups = re.findall('([A-z0-9][a-z]*)', string)
...     return '_'.join([i.lower() for i in groups])
...
>>> camel_to_snake('ABCPingPongByTheWay2KWhereIsOurBorderlands3???')
'a_b_c_ping_pong_by_the_way_2_k_where_is_our_borderlands_3'

如果你不想让数字像组的第一个字符或单独的组-你可以使用([A-z][a-z0-9]*)掩码。

我也在寻找同样问题的解决方案,只不过我需要一条链子;如。

"CamelCamelCamelCase" -> "Camel-camel-camel-case"

从这两个词的解决方案开始,我想到了以下几点:

"-".join(x.group(1).lower() if x.group(2) is None else x.group(1) \
         for x in re.finditer("((^.[^A-Z]+)|([A-Z][^A-Z]+))", "stringToSplit"))

最复杂的逻辑是避免小写第一个单词。如果你不介意改变第一个词,这里有一个更简单的版本:

"-".join(x.group(1).lower() for x in re.finditer("(^[^A-Z]+|[A-Z][^A-Z]+)", "stringToSplit"))

当然,您可以预先编译正则表达式,或者像其他解决方案中讨论的那样,使用下划线而不是连字符连接正则表达式。

避免使用库和正则表达式:

def camel_to_snake(s):
    return ''.join(['_'+c.lower() if c.isupper() else c for c in s]).lstrip('_')
>>> camel_to_snake('ThisIsMyString')
'this_is_my_string'