利用Python做一个词频统计
GitHub地址:FightingBob 【Give me a star , thanks.】
对纯英语的文本文件【Eg: 瓦尔登湖(英文版).txt】的英文单词出现的次数进行统计,并记录起来
-
代码实现
-
1 import string 2 from os import path 3 with open('瓦尔登湖(英文版).txt','rb') as text1: 4 words = [word.strip(string.punctuation).lower() for word in str(text1.read()).split()] 5 words_index = set(words) 6 count_dict = {index:words.count(index) for index in words_index} 7 with open(path.dirname(__file__) + '/file1.txt','a+') as text2: 8 text2.writelines('以下是词频统计的结果:' + '\n') 9 for word in sorted(count_dict,key=lambda x:count_dict[x],reverse=True): 10 text2.writelines('{}--{} times'.format(word,count_dict[word]) + '\n') 11 text1.close() 12 text2.close()
-
代码解析
-
获取文件,以二进制格式打开文件,用于读取内容
-
1 with open('瓦尔登湖(英文版).txt','rb') as text1:
-
-
获取单词列表
-
设置单词:单词次数的字典
- 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.】