关于后端:Python代码阅读第23篇将变量名称转换为短横线连接式命名风格

2次阅读

共计 859 个字符,预计需要花费 3 分钟才能阅读完成。

Python 代码浏览合集介绍:为什么不举荐 Python 初学者间接看我的项目源码

本篇浏览的代码实现将变量名称转换为短横线连贯式命名格调(kebab case)的性能。

本篇浏览的代码片段来自于 30-seconds-of-python。

kebab

from re import sub

def 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())

# EXAMPLES
kebab('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 格调的命名字符串。

正文完
 0