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

Posted JonyQ

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了两个文本根据索引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(\n) == len(line): #去除空行 continue else: line_ex = line.strip(‘‘).strip(\n).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) + \n null_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关联合并,将无关联信息单独输出的主要内容,如果未能解决你的问题,请参考以下文章

关联数组VS索引数组

在两个EXCEL表格中怎么把相关联的数据合并到一起

SQL怎样合并显示两个没有关联的表

Excel将两个表格关联数据

Python 两个字典(dic)中相同key合并(value分别作合成后字典key和value)

mysql两表关联排序索引问题