首页 > 代码库 > 两个文本根据索引key关联合并,将无关联信息单独输出

两个文本根据索引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-8def 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(\n) == len(line): #去除空行 continue else: line_ex = line.strip(‘‘).strip(\n).split(|) new_dict1[line_ex[0]] = line_ex[1:] return new_dict1def 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_listcustomer_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) + \nnull_list = \n.join(customer_null_list)write_dict(D:\\360Downloads\\cust_new.txt, out_lines)write_dict(D:\\360Downloads\\null_new.txt, null_list)

 

两个文本根据索引key关联合并,将无关联信息单独输出