Python 合并多个TXT文件并统计词频的实现


Posted in Python onAugust 23, 2019

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

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

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

# coding=utf-8

import re
import os

# 获取源文件夹的路径下的所有文件
sourceFileDir = 'D:\\Python\\txt\\'
filenames = os.listdir(sourceFileDir)

# 打开当前目录下的 result.txt 文件,如果没有则创建
# 文件也可以是其他类型的格式,如 result.js
file = open('D:\\Python\\result.txt', 'w')

# 遍历文件
for filename in filenames:
 filepath = sourceFileDir+'\\'+filename
 # 遍历单个文件,读取行数,写入内容
 for line in open(filepath):
  file.writelines(line)
  file.write('\n')

# 关闭文件
file.close()


# 获取单词函数定义
def getTxt():
 txt = open('result.txt').read()
 txt = txt.lower()
 txt = txt.replace(''', '\'')
 # !"@#$%^&*()+,-./:;<=>?@[\\]_`~{|}
 for ch in '!"'@#$%^&*()+,-/:;<=>?@[\\]_`~{|}':
  txt.replace(ch, ' ')
  return txt

# 1.获取单词
hamletTxt = getTxt()

# 2.切割为列表格式,'' 兼容符号错误情况,只保留英文单词
txtArr = re.findall('[a-z\''A-Z]+', hamletTxt)

# 3.去除所有遍历统计
counts = {}
for word in txtArr:
 # 去掉一些常见无价值词
 forbinArr = ['a.', 'the', 'a', 'i']
 if word not in forbinArr:
  counts[word] = counts.get(word, 0) + 1

# 4.转换格式,方便打印,将字典转换为列表,次数按从大到小排序
countsList = list(counts.items())
countsList.sort(key=lambda x: x[1], reverse=True)

# 5. 输出结果
for i in range(10):
 word, count = countsList[i]
 print('{0:<10}{1:>5}'.format(word, count))

效果如下图:

Python 合并多个TXT文件并统计词频的实现

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

# coding=utf-8
from collections import Counter

# words 为读取到的结果 list
words = ['a', 'b' ,'a', 'c', 'v', '4', ',', 'w', 'y', 'y', 'u', 'y', 'r', 't', 'w']
wordCounter = Counter(words)
print(wordCounter.most_common(10))

# output: [('y', 3), ('a', 2), ('w', 2), ('b', 1), ('c', 1), ('v', 1), ('4', 1), (',', 1), ('u', 1), ('r', 1)]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python远程桌面协议RDPY安装使用介绍
Apr 15 Python
Windows下Python使用Pandas模块操作Excel文件的教程
May 31 Python
Python中利用Scipy包的SIFT方法进行图片识别的实例教程
Jun 03 Python
Python实现八大排序算法
Aug 13 Python
Python实现连接postgresql数据库的方法分析
Dec 27 Python
Python字典及字典基本操作方法详解
Jan 30 Python
解决pycharm下os.system执行命令返回有中文乱码的问题
Jul 07 Python
python中struct模块之字节型数据的处理方法
Aug 27 Python
TensorFlow设置日志级别的几种方式小结
Feb 04 Python
django模板获取list中指定索引的值方式
May 14 Python
五种Python转义表示法
Nov 27 Python
python利用proxybroker构建爬虫免费IP代理池的实现
Feb 21 Python
Python 调用 Windows API COM 新法
Aug 22 #Python
详解Python文件修改的两种方式
Aug 22 #Python
详解python中的生成器、迭代器、闭包、装饰器
Aug 22 #Python
python支付宝支付示例详解
Aug 22 #Python
关于python3中setup.py小概念解析
Aug 22 #Python
python3 requests库文件上传与下载实现详解
Aug 22 #Python
python3使用print打印带颜色的字符串代码实例
Aug 22 #Python
You might like
PHP运行出现Notice : Use of undefined constant 的完美解决方案分享
2012/03/05 PHP
PHP Filter过滤器全面解析
2016/08/09 PHP
自制PHP框架之路由与控制器
2017/05/07 PHP
去除链接虚线全面分析总结
2006/08/15 Javascript
JQuery AJAX实现目录浏览与编辑的代码
2008/10/21 Javascript
日常收集整理的JavaScript常用函数方法
2015/12/10 Javascript
改变checkbox默认选中状态及取值的实现代码
2016/05/26 Javascript
省市区三级联动jquery实现代码
2020/04/15 Javascript
JS判断是否手机或pad访问实现方法
2016/12/09 Javascript
canvas实现钟表效果
2017/02/13 Javascript
JavaScript Base64 作为文件上传的实例代码解析
2017/02/14 Javascript
javascript图片预览和上传(兼容IE)
2017/03/15 Javascript
通过构造函数实例化对象的方法
2017/06/28 Javascript
通过一次报错详细谈谈Point事件
2018/05/17 Javascript
vue.js实现只能输入数字的输入框
2019/10/19 Javascript
Python实现子类调用父类的方法
2014/11/10 Python
Python实现股市信息下载的方法
2015/06/15 Python
使用Nginx+uWsgi实现Python的Django框架站点动静分离
2016/03/21 Python
Python编程把二叉树打印成多行代码
2018/01/04 Python
解决python os.mkdir创建目录失败的问题
2018/10/16 Python
解决pyecharts在jupyter notebook中使用报错问题
2020/04/23 Python
Python3 使用pillow库生成随机验证码
2019/08/26 Python
多版本python的pip 升级后, pip2 pip3 与python版本失配解决方法
2019/09/11 Python
Python for i in range ()用法详解
2020/09/18 Python
浅谈在django中使用filter()(即对QuerySet操作)时踩的坑
2020/03/31 Python
基于plt.title无法显示中文的快速解决
2020/05/16 Python
利用PyTorch实现VGG16教程
2020/06/24 Python
关于PyCharm安装后修改路径名称使其可重新打开的问题
2020/10/20 Python
美国最大的船只买卖在线市场:Boat Trader
2018/08/04 全球购物
社区科普工作方案
2014/06/03 职场文书
普通话宣传标语
2014/06/26 职场文书
老干部座谈会主持词
2015/07/03 职场文书
廉洁自律准则学习心得体会
2016/01/13 职场文书
MySQL修改默认引擎和字符集详情
2021/09/25 MySQL
Nginx流量拷贝ngx_http_mirror_module模块使用方法详解
2022/04/07 Servers
element tree树形组件回显数据问题解决
2022/08/14 Javascript