layout: posttitle: Python 合并多个TXT文件并统计词频
subtitle: Python 合并多个TXT文件并统计词频
date: 2019-08-22
author: he xiaodong
header-img: img/default-post-bg.jpg
catalog: true
tags:
- Python
- 合并多个txt文件
- 统计词频
- 读取txt

需求是:针对三篇英文文章进行分析,计算出现次数最多的 10 个单词

逻辑很清晰简单,不算难,使用 python 读取多个 txt 文件,将文件的内容写入新的 txt 中,然后对新 txt 文件进行词频统计,得到最终结果。

代码如下:(在Windows 10,Python 3.7.4环境下运行通过)

  1. # coding=utf-8
  2. import re
  3. import os
  4. # 获取源文件夹的路径下的所有文件
  5. sourceFileDir = 'D:\\Python\\txt\\'
  6. filenames = os.listdir(sourceFileDir)
  7. # 打开当前目录下的 result.txt 文件,如果没有则创建
  8. # 文件也可以是其他类型的格式,如 result.js
  9. file = open('D:\\Python\\result.txt', 'w')
  10. # 遍历文件
  11. for filename in filenames:
  12. filepath = sourceFileDir+'\\'+filename
  13. # 遍历单个文件,读取行数,写入内容
  14. for line in open(filepath):
  15. file.writelines(line)
  16. file.write('\n')
  17. # 关闭文件
  18. file.close()
  19. # 获取单词函数定义
  20. def getTxt():
  21. txt = open('result.txt').read()
  22. txt = txt.lower()
  23. txt = txt.replace('’', '\'')
  24. # !"@#$%^&*()+,-./:;<=>?@[\\]_`~{|}
  25. for ch in '!"’@#$%^&*()+,-/:;<=>?@[\\]_`~{|}':
  26. txt.replace(ch, ' ')
  27. return txt
  28. # 1.获取单词
  29. hamletTxt = getTxt()
  30. # 2.切割为列表格式,'’ 兼容符号错误情况,只保留英文单词
  31. txtArr = re.findall('[a-z\'’A-Z]+', hamletTxt)
  32. # 3.去除所有遍历统计
  33. counts = {}
  34. for word in txtArr:
  35. # 去掉一些常见无价值词
  36. forbinArr = ['a.', 'the', 'a', 'i']
  37. if word not in forbinArr:
  38. counts[word] = counts.get(word, 0) + 1
  39. # 4.转换格式,方便打印,将字典转换为列表,次数按从大到小排序
  40. countsList = list(counts.items())
  41. countsList.sort(key=lambda x: x[1], reverse=True)
  42. # 5. 输出结果
  43. for i in range(10):
  44. word, count = countsList[i]
  45. print('{0:<10}{1:>5}'.format(word, count))

效果如下图:

2019-08-22-Python 合并多个TXT文件并统计词频 - 图1

另一种更简单的统计词频的方法:

  1. # coding=utf-8
  2. from collections import Counter
  3. # words 为读取到的结果 list
  4. words = ['a', 'b' ,'a', 'c', 'v', '4', ',', 'w', 'y', 'y', 'u', 'y', 'r', 't', 'w']
  5. wordCounter = Counter(words)
  6. print(wordCounter.most_common(10))
  7. # output: [('y', 3), ('a', 2), ('w', 2), ('b', 1), ('c', 1), ('v', 1), ('4', 1), (',', 1), ('u', 1), ('r', 1)]

最后恰饭 阿里云全系列产品/短信包特惠购买 中小企业上云最佳选择 阿里云内部优惠券