背景:
python读取数据(如数据库数据)往往是list形式的,在进行数据处理时(如格式化的kafka、或者json形式),由于编码风格要求代码一定是驼峰或下划线等的一种,转换成另一种形式往往会使用如data_dict['xxx']='yyyy'的形式,这样的缺点:
- 1、可扩展性不好
- 2、硬编码
- 3、重复性代码多
- 4、不美观
针对以上缺点做了如下工具类:
方法:
1、定义数据格式类:key的名字与list索引的对应位置
2、定义工具类:自动识别数据格式类的变量名称
3、动态获取变量key:根据相应的转换规则(驼峰->x下划线? ?下划线->驼峰)进行转换
4、转换成字典或者json
精髓:
- 1、__dict__
- 2、setattr
- 3、类初始化
具体实现如下:
import re
class User(object):
USER_NAME = 0
USER_SOURCE = 1
USER_AGE = 2
USER_SCORE = 3
class Employee:
employeeName = 0
employeeId = 1
employeeDepartment = 2
employeeTitle = 3
class FormatDictTool(object):
"""
将list数据(下划线式)转换成驼峰式的字典结构
"""
def __init__(self, class_name, trans_type='camel'):
func = self._to_lower_camel
if trans_type == 'snake':
func = self._to_snake
for key, index in class_name.__dict__.items():
if '__' in key:
continue
new_key = func(key)
setattr(self, new_key, index)
@staticmethod
def _to_lower_camel(name: str):
"""下划线转小驼峰法命名"""
return re.sub('_([a-zA-Z])', lambda m: (m.group(1).upper()), name.lower())
def _to_snake(self, name: str) -> str:
"""驼峰转下划线"""
if '_' not in name:
name = re.sub(r'([a-z])([A-Z])', r'\1_\2', name)
else:
raise ValueError(f'{name}字符中包含下划线,无法转换')
return name.lower()
def list2dict(self, arrays):
return {key: arrays[index] for key, index in self.__dict__.items()}
if __name__ == '__main__':
tool = FormatDictTool(class_name=User)
user_data_list = [['name1', 'source1', 'user_source1', 20.3], ['name2', 'source2', 'user_source2', 50]]
print('User:')
for data in user_data_list:
print(tool.list2dict(data))
tool = FormatDictTool(class_name=Employee, trans_type='snake')
employee_data_list = [['name1', 'id1', 'department1', 'title1'], ['name2', 'id2', 'department2', 'title2']]
print('Employee:')
for data in employee_data_list:
print(tool.list2dict(data))
结果:
User:
{'userName': 'name1', 'userSource': 'source1', 'userAge': 'user_source1', 'userScore': 20.3}
{'userName': 'name2', 'userSource': 'source2', 'userAge': 'user_source2', 'userScore': 50}
Employee:
{'employee_name': 'name1', 'employee_id': 'id1', 'employee_department': 'department1', 'employee_title': 'title1'}
{'employee_name': 'name2', 'employee_id': 'id2', 'employee_department': 'department2', 'employee_title': 'title2'}
参考:
python实现驼峰式命名与下划线命名互相转换_OSinooO的博客-CSDN博客_python 驼峰转下划线
|