Python代码阅读合集介绍:为什么不推荐Python初学者直接阅读项目源码实现变量名转换函数命名风格(kebabcase)用于连字符。本文阅读的代码片段来自30-seconds-of-python。kebabfrom重新导入subdefkebab(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]+",lambdamo:''+mo.group(0).lower(),s).split())#EXAMPLESkebab('camelCase')#'camel-case'kebab('sometext')#'some-text'kebab('some-mixed_stringWithspaces_underscores-and-hyphens')#'some-mixed-string-with-spaces-underscores-and-hyphens'kebab('AllThe-smallThings')#"all-the-small-things"函数kebab接收一个字符串,使用正则表达式warp,将字符串打散成单词,并以-作为分隔符组合起来。函数最内层的re.sub(pattern,repl,string,count=0,flags=0)函数使用正则表达式匹配字符串中的单词,然后使用repl函数lambdamo:''+mo.group(0).lower()对匹配到的单词进行处理,将单词用空格分隔,并转为小写。repl函数将匹配信息作为mo,andmo.传递给函数。group(0)返回匹配的字符串。第二层的子函数先用空格替换各种空白字符、下划线、破折号。然后根据空格将字符串拆分为单词。最后,该函数将分隔的单词与破折号“-”连接起来,以获取kebab大小写样式的命名字符串。
