dealCarBrandChange.py 5.79 KB
import logging
import pandas as pdas
import os
import chardet
from datetime import datetime, timezone
import json
from collections import OrderedDict

import openpyxl
from openpyxl import Workbook

from djcardrenewal.common.dbase.MysqlHelper import MysqlHelper
from djcardrenewal.common.dbase import DbConect
from djcardrenewal.common.sqlcontent import DjSql
from djcardrenewal.common.sqlcontent import CurMonthYzl
from djcardrenewal.common.string.StringBuilder import StringBuilder


print("sys config " + __name__)
log_name = './log/bizcommon/dealCarBrandChange.log'
log_format = '[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]'
log_level = logging.DEBUG
log_mode = 'a'
logging.basicConfig(filename=log_name, format=log_format, level=log_level, filemode=log_mode)

class DealDeviceLocationMain:

    handleDescription = ''
    handleMonth = ''
    hmonth = ''
    module_file_path = ''
    defaultExportReleasePath = ''

    scrmDb = None

    # 定义一个字典数据
    dicMapper = {'2366':'2695','2431':'2695','2691':'2695','2692':'2698','2697':'2698'}

    def __init__(self, handle_month):
        logging.info("init construct bean")
        self.handleDescription = "---业务导出恒信数据---脚本执行..."
        self.handleMonth = handle_month
        self.hmonth = handle_month.replace('-', '')[2:6]
        self.scrmDb = MysqlHelper(DbConect.release_scrm_account_db)

    def initCurrentMonthTable(self):
        logging.info("初始化:暂无操作")

    # 定义修改函数
    def modify_data(self, x):
        # 进行批量修改的逻辑
        if x is None:
            return x
        return x.replace("M{", "").replace("}", "")

    # 定义修改函数
    def modify_float_data(self, x):
        # 进行批量修改的逻辑
        if x is None:
            return 0
        current = str(x).replace("`", "").replace(' ', '')
        if current == '':
            return 0
        return current

    # 定义修改函数
    def dealContentFile(self):
        # and pm.merchantNo=44212086
        selectSql = 'select pm.merchantNo,pm.merchant_brand,pm.merchant_brand_main from platform_merchant pm where (pm.merchant_brand is not null or pm.merchant_brand_main is not null)  ;'
        # 1、读取文件内容
        scrmAccountDb = self.scrmDb.execute_select(selectSql)

        # 初始化一个空的DataFrame,定义列名
        data_list = []
        for rowData in scrmAccountDb:
            merchantId = rowData[0]
            merchantBrand = rowData[1]
            merchantBrandMain = rowData[2]

            brandReplaced = False
            brandMainReplaced = False
            if merchantBrand is not None and merchantBrand != '':
                # 分割字符串为列表
                elements = merchantBrand.split(',')
                # 使用字典映射替换列表中的元素,并记录是否有元素被替换
                mapped_elements = []
                for element in elements:
                    mapped_element = self.dicMapper.get(element, element)
                    if mapped_element != element:
                        brandReplaced = True
                    mapped_elements.append(mapped_element)

                # 将处理后的列表元素重新组合成字符串
                output_merchantBrand = ','.join(mapped_elements)

            if merchantBrandMain is not None and merchantBrandMain != '':
                # 使用正则表达式分割字符串,匹配逗号或分号作为分隔符
                parts = merchantBrandMain.split(';')
                output_parts = []
                for part in parts:
                    # 分割每个部分内部的逗号
                    numbers = part.split(',')
                    # 替换并去重
                    mapped_numbers_curr = list(OrderedDict.fromkeys(self.dicMapper.get(num, num) for num in numbers))  # 使用OrderedDict去重并保持顺序
                    mapped_numbers = []
                    for num in mapped_numbers_curr:
                        if num is not None and num!='':
                            mapped_numbers.append(num)
                    if len(mapped_numbers)==0:
                        continue;
                    # 检查是否有所替换(去重后的列表与原列表比较)
                    if len(mapped_numbers) != len(set(numbers)) or any(mapped != num for num, mapped in zip(numbers, mapped_numbers)):
                        brandMainReplaced = True
                    # 过滤掉去重后为空的子串
                    if mapped_numbers:
                        output_part = ','.join(mapped_numbers)
                        output_parts.append(output_part)
                # 合并处理后的子串
                output_merchantBrandMain = ';'.join(output_parts)

            if brandReplaced or brandMainReplaced:
                data_list.append({'MerchantID': merchantId, 'MerchantBrand': output_merchantBrand, 'MerchantBrandMain': output_merchantBrandMain})
            output_merchantBrand=''
            output_merchantBrandMain=''
        # 使用pd.concat()将数据列表转换为DataFrame
        data_df = pdas.DataFrame(data_list)
        data_df.to_excel(self.defaultExportReleasePath, index=False)

if __name__ == "__main__":
    handle_month = '2021-2024'
    dedRes = False
    diRes = False
    urRes = False

    print('==========================处理账户中心商户对应的品牌信息==========================')

    
    #启动初始化
    dealMain = DealDeviceLocationMain(handle_month)
    logging.info("start handle" + dealMain.handleDescription + ' the month:' + dealMain.handleMonth)

    dealMain.module_file_path = 'D:/work_doc/dataexport/gpslocation/gpslocation20240410.xlsx'
    dealMain.defaultExportReleasePath = 'D:/work_doc/dataexport/accountbrand/gpslocation20240513-result.xlsx'

    dealMain.dealContentFile() 
    print('导出完成。')