鱼C论坛

 找回密码
 立即注册
查看: 1669|回复: 3

[已解决]求助---A文件中的词汇出现在B文件中的统计

[复制链接]
发表于 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


  1. with open('a.txt', encoding='utf8') as f:
  2.     s = set(f.read().split('\n'))

  3. d = {}
  4.             
  5. with open('b.txt', encoding='utf8') as f:
  6.     lines = f.read().split('\n')
  7.     for line in lines:
  8.         arr = line.split(',')
  9.         order, content, serial = arr[0], arr[1], arr[2]
  10.         if serial in s:
  11.             if serial not in d:
  12.                 d[serial] = {'order': [], 'content': []}
  13.             d[serial]['order'].append(order)
  14.             d[serial]['content'].append(content)

  15. def get_str(item):
  16.     return '[' + ','.join(item) + ']'
  17.    
  18. with open('c.txt', mode='w', encoding='utf8') as f:
  19.     contents = []
  20.     for key in d.keys():
  21.         order, content = d[key]['order'], d[key]['content']
  22.         contents.append(','.join([key, get_str(order), get_str(content)]))

  23.     f.write('\n'.join(contents))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-11-7 02:57

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表