Python练习册第06题

首先何谓最重要的词???
我就单纯地取出现频率最高的单词吧,管它呢

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是大家觉得最重要的词呢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值