Pythonバッチデータ処理 - アンダースコアとキャメルケースの相互変換

バックグラウンド:

Python で読み取られるデータ (データベース データなど) はリスト形式であることが多く、データ (フォーマットされた kafka 形式や json 形式など) を処理する場合、コーディング スタイルではコードがハンプまたはアンダースコアのいずれかである必要があります。あるフォームでは、data_dict['xxx']='yyyy' などの形式がよく使用されますが、次のような欠点があります。

  • 1. スケーラビリティが低い
  • 2. ハードコード化
  • 3. 反復コードが多い
  • 4. 見苦しい

上記の欠点を考慮して、次のツール クラスが作成されます。

方法:

1. データ形式クラスを定義します: キーの名前とリスト インデックスの対応する位置

2. ツールクラスを定義します。データフォーマットクラスの変数名を自動的に識別します。

3. 変数キーを動的に取得します。対応する変換ルールに従って変換します (ハンプ -> x アンダースコア アンダースコア -> ハンプ)

4.辞書またはJSONに変換

エッセンス:

  • 1、__dict__
  • 2、設定
  • 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 はこぶ形式の命名とアンダースコア命名の間の変換を実現します

おすすめ

転載: blog.csdn.net/qq_19446965/article/details/124359240