首先何谓最重要的词???
我就单纯地取出现频率最高的单词吧,管它呢
import os, re
if __name__ == '__main__':
words = {} #字典用来统计每篇文章里各单词出现的次数
favorite_word = [] #存放每篇文章里出现频率最高的词,注意可能出现并列第一的可能
file_name_list = os.listdir()
for file_name in file_name_list:
words.clear()
favorite_word.clear()
#只读取txt文件
if(re.search('.txt$', file_name)):
#用04题相似的方法,只保留纯英文单词
with open(file_name, 'r', encoding = 'utf-8') as file:
while True:
buf = file.readline()
if buf == '':
break
buf = re.sub(r'[^a-zA-z0-9 ]', ' ', buf).split(' ')
for j in buf:
if j.isalpha():
#去除大小写的影响,不管大小写都算同一个单词
j = j.lower()
#字典的setdefault方法,如果不存在key,则新建key=None
count = words.setdefault(j)
if count == None:
words[j] = 1
else:
#如果已经存在key,则记数+1
words[j] = count + 1
#取得最高频率数
n = sorted(words.values())[-1]
#遍历字典,取出最高频率数的单词放进list中,包括并列第一的
for key, value in words.items():
if value == n:
favorite_word.append(key)
#按"文件名: 最高频率单词"的形式将统计结果写入文件中
with open('statistic.txt', 'a', encoding = 'utf-8') as file_out:
file_out.write(file_name + ': ')
for i in favorite_word:
file_out.write(i + ' ')
file_out.write('\n')
样本文件我还是取了stack overflow上的privacy policy,并把它分割成9个txt文件(懒
运行结果:
1.txt: and
2.txt: and
3.txt: and
4.txt: and we
5.txt: and
6.txt: and
7.txt: the
8.txt: to
9.txt: privacy
看来and是大家觉得最重要的词呢