天天看點

兩個文本根據索引key關聯合并,将無關聯資訊單獨輸出

原始兩個文本
customer.txt:23115823|3115823|aaaaaa|20030819000000|20040420000000|A|CTC-BJ|B23|0|N|0|0      
custservice.txt:23115823|fw001|N|1|999912000000|0      
腳本執行組合後:23115823~_~23115823~_~aaaaaa~_~20030819000000~_~20040420000000~_~0~_~fw001~_~N~_~1~_~4~_~0





# coding=utf-8
def creat_dict(customer_read_path):
  """将文本轉換為字典,key為文本ID索引,兩個文本的關聯值;value為其他内容"""
    with open(customer_read_path, 'r') as customer:
        new_dict1 = {}
        for line in customer.readlines():
            if line.count('
') == len(line):  #去除空行
                continue
            else:
                line_ex = line.strip('').strip('
').split('|')
                new_dict1[line_ex[0]] = line_ex[1:]
    return new_dict1


def write_dict(customer_write_path, content):
    with open(customer_write_path, 'w') as customer:
        customer.write(content)


def creat_new_null_list(customer_dict,custservice_dict):
   """通過關聯相同的key合并兩個字典"""
    customer_new_list = []
    customer_null_list = []
    for customer_key in customer_dict.keys():
        if customer_key in custservice_dict.keys():
            customer_new_list.append([customer_key] + customer_dict[customer_key] + custservice_dict[customer_key])
        else:
            customer_null_list.append(customer_key)
    return customer_new_list,customer_null_list

customer_dict1 = creat_dict('D:\360Downloads\customer.txt')
custservice_dict1 = creat_dict('D:\360Downloads\custservice.txt')
if len(customer_dict1) != len(custservice_dict1):
    print('customer and custservice does not match')
    customer_new_list, customer_null_list = creat_new_null_list(customer_dict1,custservice_dict1)
out_lines = ''
roamstatus = (lambda x: '4' if x == '0' else '3' if x == '1' else x)   #用于原始清單中值判斷替換為新值
fansuan = (lambda x: '5' if x == 'Y' else '0')
custstatus = (lambda x: '0' if x == 'A' or x == 'N' else '1' if x == 'C' else '2' if x == 'O' else '0')
for cu in customer_new_list: #将新list根據轉換後組合
    cu[16] = roamstatus(cu[16])
    cu[9] = fansuan(cu[9])
    cu[5] = max(custstatus(cu[5]), custstatus(cu[13]))
    cu_new_list = cu[:6] + cu[12:15] + [cu[16]] + [cu[9]]
    out_lines += '~_~'.join(cu_new_list) + '
'
null_list = '
'.join(customer_null_list)
write_dict('D:\360Downloads\cust_new.txt', out_lines)
write_dict('D:\360Downloads\null_new.txt', null_list)