变量命名风格转换(Python)

发布时间 2024-01-09 21:54:25作者: 孙牧

开发过程中对接接口经常遇到命名风格的问题,不同系统的风格,想要保持自身代码风格统一,不可避免的需要转换命名风格

代码

import re


class NameStyleConve:
    """
        变量命名风格转换,要求处理的是字符串不是字典,使用 json.dumps(data_dict)
    """
    _snake_key_name = r'(\,\s[\"])(\S)(\S+?)([\"]\:)'
    _camel_key_name = r'(\,\s[\"])(\S)(\S+?)([\"]\:)'

    @classmethod
    def snake_to_camel(cls, data: str):
        """ 下划线转换小驼峰 """
        def _conv_fun(x):
            return re.sub(r"_([a-z])", lambda m: m.group(1).upper(), x.group(0))
        return re.sub(cls._snake_key_name, _conv_fun, data)

    @classmethod
    def snake_to_camel2(cls, data: str):
        """ 下划线转换大驼峰 """
        def _conv_fun(x):
            new_key_name = re.sub(r"_([a-z])", lambda m: m.group(1).upper(), x.group(3))
            return f"{x.group(1)}{x.group(2).upper()}{new_key_name}{x.group(4)}"
        return re.sub(cls._snake_key_name, _conv_fun, data)

    @classmethod
    def camel_to_snake(cls, data: str):
        """ 驼峰转换下划线 """
        def _conv_fun(x):
            new_key_name = re.sub(r'([A-Z][a-z])', lambda m: f"_{m.group(1)}", x.group(3))
            return f"{x.group(1)}{x.group(2)}{new_key_name}{x.group(4)}".lower()
        return re.sub(cls._camel_key_name, _conv_fun, data)

使用


data = {
   "min_position": 5,
   "has_more_items": false,
   "items_html": "Bike",
   "new_latent_count": 1,
   "data": {
      "length": 29,
      "text": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.",
      "is_disable": 2
   }
}

res = NameStyleConve.snake_to_camel(data)
print(res)