利用Python做一个词频统计
GitHub地址:FightingBob 【Give me a star , thanks.】
词频统计
对纯英语的文本文件【Eg: 瓦尔登湖(英文版).txt】的英文单词出现的次数进行统计,并记录起来
代码实现
import string
from os import path
with open('瓦尔登湖(英文版).txt','rb') as text1:
words = [word.strip(string.punctuation).lower() for word in str(text1.read()).split()]
words_index = set(words)
count_dict = {index:words.count(index) for index in words_index}
with open(path.dirname(__file__) + '/file1.txt','a+') as text2:
text2.writelines('以下是词频统计的结果:' + '\n')
for word in sorted(count_dict,key=lambda x:count_dict[x],reverse=True):
text2.writelines('{}--{} times'.format(word,count_dict[word]) + '\n')
text1.close()
text2.close()
代码解析
获取文件,以二进制格式打开文件,用于读取内容
1 with open('瓦尔登湖(英文版).txt','rb') as text1:
获取单词列表
先读取内容
- content = text1.read()
再获取单词列表(使用split() 通过指定分隔符对字符串进行切片)
- words = content.split()
单词大写改小写,去掉单词前后符号
- word,strip(string.punctuation).lower()
去除重复的单词
- words_index = set(words)
设置单词:单词次数的字典
- count_dict = {index:words.count(index) for index in words_index}
写入词频统计
先创建文件,获取当前目录,并以追加写入的方式写入
- with open(path.dirname(__file__) + '/file1.txt','a+') as text2:
换行写入
- text2.writelines('以下是词频统计的结果:' + '\n')
对单词进行排序,根据次数从大到小【key=lambda x:count_dict[x]以值排序】
- sorted(count_dict,key=lambda x:count_dict[x],reverse=True)
换行写入词频
- text2.writelines('{}--{} times'.format(word,count_dict[word]) + '\n')
关闭资源
- text1.close()
- text2.close()
GitHub地址:FightingBob 【Give me a star , thanks.】