Python recipe(7): 命名规则转换

代码何在?

div css xhtml xml Example Source Code Example Source Code [http://www.cnblogs.com/tomsheep/]
'''
Created on 2010-5-21

@author: lk
'''
import re,string

#cw: capwords
#us: underscore
#mc: mixed-case
#lw: lower-case

def cw2us(x):
    return re.sub(r'(?<=[a-z])[A-Z]|(?<!^)[A-Z](?=[a-z])', r'_\g<0>', x).lower()

def us2mc(x):
    return re.sub(r'_([a-z])', lambda match:match.group(1).upper(), x)

def mc2us1(x):
    return cw2us(x)

def us2cw(x):
#    return ''.join(map(string.capitalize,x.split('_')))
    s = us2mc(x)
    return s[0].upper()+s[1:]
def mc2cw1(x):
    return x[0].upper()+x[1:]
def cw2mc1(x):
    return x[0].lower()+x[1:]


def any2lw(x):
    lw = x.split('_')
    if(len(lw)>1): #underscore style
        return map(string.lower, lw)
    #otherwise
    pieces = re.split('([A-Z])',x)
    if pieces[0]:#begin with a non-capital char
        pieces = ['']+pieces #for the method below
    else:
        pieces = pieces[1:]
        
    return [pieces[i].lower()+pieces[i+1] for i in range(0, len(pieces), 2)]

def lw2us(x):return '_'.join(x)
def lw2cw(x):return ''.join(map(string.capitalize, x))
def lw2mc(x):return x[0]+lw2cw(x[1:])

def any2us(x): return lw2us(any2lw(x))
def any2cw(x): return lw2cw(any2lw(x))
def any2mc(x): return lw2mc(any2lw(x))

if __name__ == '__main__':
    x = "ILikeHTML"
    y = cw2us(x)
    z = us2mc(y)
    
    w = us2cw(y)
    print x,y,z,w
#    print re.split('([A-Z])',x)
#    print x.split('([A-Z])')

    print any2cw(x)
    print any2mc(x)
    print any2us(x)
    print any2lw(x)

以上代码改写自Python Cookbook 3-16

概述:

    在不同的命名规则(如下划线分割法、驼峰法、词汇首字母大写法等)之间相互转换。给出两套方案:第一种利用re模块一对一地转换,这种方法不太具有拓展性,一旦命名规则种类增多,需添加大量转换函数;第二种提供了一种通用的中间形式,即小写list,只需提供各种命名规则与小写list之间的转换规则即可。(本代码第二种实现与第一种效果略有不同,主要体现在连续大写字母的处理上)

代码说明:

1.正则表达式中的“0宽断言”:

(?=exp): 在断言自身后匹配exp

(?>=exp): 在断言自身前匹配exp

(?!exp): 在断言自身后不能出现exp匹配

(?<!exp)在断言自身前不能出现exp匹配

更多正则表达式资料见:正则表达式30分钟入门教程

2.在cw2us函数中,使用re.sub函数时第二个参数传了 r’_\g<0>’, 这里的g<0>既表示match.group(0)

3.re.split和string对象的split区别在于后者不能使用正则表达式……汗,原来先入为主以为可以……

4.过去一直想为什么很多对象已经提供的函数,模块又要提供一遍,比如re和string;现在感觉也许一定程度是为了书写便捷,比如map用起来很方便(- -|||露怯……随着学习深入以后应该会有新的认识……)

posted on 2010-05-21 23:41  tomsheep  阅读(502)  评论(0编辑  收藏  举报

导航