python笔记11:读取文本英文实现词频统计


 

import string

with open('E:\Python教程与安装程序\Walden.txt', 'r') as text:
    words = [raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()]
    words_index = set(words)
    counts_dict = {index: words.count(index) for index in words_index}

for word in sorted(counts_dict, key=lambda x: counts_dict[x], reverse=True):
    print('{}--{} times'.format(word, counts_dict[word]))

代码说明注释:

首先,导入模块string。目的是将string.punctuation打印出来。这里面包含了所有的标点符号。
在文字的首位去掉了连在一起的标点符号。并将首字母大写的单词转为小写。
接下来,将列表用set函数转换为集合,自动去除了其中所有重复的元素。
接下来,创建了一个以单词为键名,出现频率为键值的字典。
最后,打印整理后的函数,其中key=lambda x:counts_dict[x]是匿名函数表达式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

m0_64880493_江哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值