当前位置:网站首页>txt文件英语单词词频统计
txt文件英语单词词频统计
2022-08-05 05:25:00 【回首思】
目录
一、需求分析
把txt文件里的英语单词按照出现次数排序并生成csv文件,如果次数相同按照单词的md5值来排序
二、相关库列表
- pandas
- re
- collections
- hashlib
三、代码在此
- 打开文件
txt_file = open(file_path, 'r')
- 读取文件内容
txt_data = txt_file.read()
- 字母全小写
txt_lower = txt_data.lower()
- 正则表达式去特殊符号
# 正则表达式去除特殊符号 punc = '~`!#$%^&*()_+-=|\';":/.,?><~·!@#¥%……&*()——+-=“:’;、。,?》《{}\n' # 调用正则表达 txt_query = re.sub(r"[%s]+" % punc, "", txt_lower)
- 调用统计库对词频统计
# 使用空格来对字符串进行裁切 txt_list = txt_query.split(' ') # 调用统计库来对词频进行统计 word = Counter(txt_list)
- 把每个单词的信息写入到一个列表
# 创建一个列表来接收DataFrame原型 pa_list = [] # 把键、值和根据键名生成的md5写入原型里 for key, value in word.items(): pa_list.append([key, value, hashlib.md5(key.encode('utf-8')).hexdigest()])
- 调用pandas完成排序和文件导出
# 生成DataFrame pd_data = pd.DataFrame(pa_list) # 根据值和md5进行排序 dataexclex = pd_data.sort_values([1, 2]) # 把文件导出 dataexclex.to_csv(f'./{new_file_name}.csv')
- 完整代码
import pandas as pd import re from collections import Counter import hashlib def Word_frequency_statistics(file_path,new_file_name): # 打开文件 txt_file = open(file_path, 'r') # 读取文件内容 txt_data = txt_file.read() # 字母小写化 txt_lower = txt_data.lower() # 正则表达式去除特殊符号 punc = '~`!#$%^&*()_+-=|\';":/.,?><~·!@#¥%……&*()——+-=“:’;、。,?》《{}\n' # 调用正则表达 txt_query = re.sub(r"[%s]+" % punc, "", txt_lower) # 使用空格来对字符串进行裁切 txt_list = txt_query.split(' ') # 调用统计库来对词频进行统计 word = Counter(txt_list) # 创建一个列表来接收DataFrame原型 pa_list = [] # 把键、值和根据键名生成的md5写入原型里 for key, value in word.items(): pa_list.append([key, value, hashlib.md5(key.encode('utf-8')).hexdigest()]) # 生成DataFrame pd_data = pd.DataFrame(pa_list) # 根据值和md5进行排序 dataexclex = pd_data.sort_values([1, 2]) # 把文件导出 dataexclex.to_csv(f'./{new_file_name}.csv') # 要词频统计的文件路径 file_path = '' # 导出时的文件名称 new_file_name = '' # 调用函数统计词频 Word_frequency_statistics(file_path,new_file_name)
四、一些问题
我只试过wav文件,mp3文件一个也可以,前提是文件夹里的文件全是要参与的文件,安装库的时候遇到问题简易回退一个大版本0.9.0=>0.8.0实际体验没多大区别。
边栏推荐
猜你喜欢
LeetCode练习及自己理解记录(1)
设置文本向两边居中展示
数组&的运算
Teach you simple steps to achieve industrial raspberries pie properly installed RS232 USB drive
transport layer protocol
Cocos Creator Mini Game Case "Stick Soldier"
config.js相关配置汇总
Wireshark packet capture and common filtering methods
el-progress实现进度条颜色不同
Growth: IT Operations Trends Report
随机推荐
VSCode编写OpenCV
scikit-image图像处理笔记
selenium learning
人人AI(吴恩达系列)
媒体查询、rem移动端适配
Nacos集群的搭建过程详解
System basics - study notes (some command records)
Billions of IT operations in the market, the product by strength to speak
Some basic method records of commonly used languages in LeetCode
通过反射获取Class对象的四种方式
LaTeX使用frame制作PPT图片没有标号
Chengyun Technology was invited to attend the 2022 Alibaba Cloud Partner Conference and won the "Gathering Strength and Going Far" Award
LeetCode中常用语言的一些基本方法记录
LeetCode刷题记录(2)
wc, grep, tar, vi/vim
教您简单几步实现工业树莓派正确安装RS232转USB驱动
DisabledDate date picker datePicker
cs231n学习记录
By solving these three problems, the operation and maintenance efficiency will exceed 90% of the hospital
vs2017关于函数命名方面的注意事项