|
|
发表于 2022-3-24 15:15:16
|
显示全部楼层
本楼为最佳答案
本帖最后由 qbw941054510 于 2022-3-24 21:40 编辑
给一个大致的思路:
1. 用 set 存 A.txt 中的所有编号
2. 设一个 dict,键为编号,值为 list
3. 遍历 B.txt 的每一条,用 split 提取编号,如果编号在 set 中,那么存到 dict 里
4. 遍历 dict,按特定格式存到 C.txt
- with open('a.txt', encoding='utf8') as f:
- s = set(f.read().split('\n'))
- d = {}
-
- with open('b.txt', encoding='utf8') as f:
- lines = f.read().split('\n')
- for line in lines:
- arr = line.split(',')
- order, content, serial = arr[0], arr[1], arr[2]
- if serial in s:
- if serial not in d:
- d[serial] = {'order': [], 'content': []}
- d[serial]['order'].append(order)
- d[serial]['content'].append(content)
- def get_str(item):
- return '[' + ','.join(item) + ']'
-
- with open('c.txt', mode='w', encoding='utf8') as f:
- contents = []
- for key in d.keys():
- order, content = d[key]['order'], d[key]['content']
- contents.append(','.join([key, get_str(order), get_str(content)]))
- f.write('\n'.join(contents))
复制代码 |
|