在Python中,如何简化从下划线到camelcase的转换?

2024-04-30 04:22:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我在下面编写了一个函数,它将下划线转换为camelcase,第一个单词用小写字母表示,即“get this value”->;“getThisValue”。此外,我还要求保留前导下划线和尾随下划线,以及双(三重等)下划线(如果有的话),即

"_get__this_value_" -> "_get_ThisValue_".

代码:

def underscore_to_camelcase(value):
    output = ""
    first_word_passed = False
    for word in value.split("_"):
        if not word:
            output += "_"
            continue
        if first_word_passed:
            output += word.capitalize()
        else:
            output += word.lower()
        first_word_passed = True
    return output

我感觉上面的代码是用非Pythonic风格编写的,尽管它工作正常,所以我想看看如何简化代码并使用列表理解等方法编写它


Tags: 函数代码gtoutputgetifvaluethis
3条回答

我个人更喜欢正则表达式。这是一个为我做的把戏:

import re
def to_camelcase(s):
    return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s)

使用unutbu的测试:

tests = [('get__this_value', 'get_ThisValue'),
         ('_get__this_value', '_get_ThisValue'),
         ('_get__this_value_', '_get_ThisValue_'),
         ('get_this_value', 'getThisValue'),
         ('get__this__value', 'get_This_Value')]

for test, expected in tests:
    assert to_camelcase(test) == expected

你的密码没问题。我认为你要解决的问题是if first_word_passed看起来有点难看。

解决这个问题的一种方法是使用发电机。我们可以很容易地使第一个条目返回一件事,而所有后续条目返回另一件事。由于Python有一级函数,我们可以让生成器返回我们要用来处理每个单词的函数。

我们只需要使用the conditional operator,这样就可以处理在列表理解中由双下划线返回的空白条目。

因此,如果我们有一个单词,我们调用生成器以获取用于设置大小写的函数,如果我们没有,我们只使用_使生成器保持不变。

def underscore_to_camelcase(value):
    def camelcase(): 
        yield str.lower
        while True:
            yield str.capitalize

    c = camelcase()
    return "".join(c.next()(x) if x else '_' for x in value.split("_"))

除了第一个字是小写外,这一个是有效的。

def convert(word):
    return ''.join(x.capitalize() or '_' for x in word.split('_'))

(我知道这并不完全是你想要的,而且这个线程已经很老了,但是由于在Google上搜索这样的转换时它非常突出,我想我会添加我的解决方案,以防对其他人有帮助)。

相关问题 更多 >