Python 代码浏览合集介绍:为什么不举荐Python初学者间接看我的项目源码
本篇浏览的代码实现将变量名称转换为短横线连贯式命名格调(kebab case
)的性能。
本篇浏览的代码片段来自于30-seconds-of-python。
kebab
from re import subdef kebab(s): return '-'.join( sub(r"(\s|_|-)+"," ", sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+", lambda mo: ' ' + mo.group(0).lower(), s)).split())# EXAMPLESkebab('camelCase') # 'camel-case'kebab('some text') # 'some-text'kebab('some-mixed_string With spaces_underscores-and-hyphens') # 'some-mixed-string-with-spaces-underscores-and-hyphens'kebab('AllThe-small Things') # "all-the-small-things"
函数kebab接管一个字符串,应用正则表达式将字符串变形、分解成单词,并加上-
作为分隔符组合起来。
函数最内层的re.sub(pattern, repl, string, count=0, flags=0)
函数应用正则表达式将字符串中的单词匹配进去。而后应用repl
函数lambda mo: ' ' + mo.group(0).lower()
来解决匹配到的单词,将单词用空格离开,并转换成小写。repl
函数将匹配信息作为mo
传入函数,mo.group(0)
返回匹配到的字符串。
第二层sub
函数将各种空白字符、下划线以及短横线都先对立替换成空格。而后再将字符串依据空格宰割成单词。
最初函数将宰割进去的单词应用短横线'-'
连接起来,即可失去kebab case
格调的命名字符串。