python代码简单实现一个词频统计

python代码简单实现一个词频统计


path = 'C://Users/DELL/Desktop/Text.txt'
with open(path, 'r') as text:
    words = text.read().split()
    print(words)
    for word in words:
        print('{}-{}times'.format(word, words.count(word)))


import string  #引入string模块

path = 'C://Users/DELL/Desktop/Text.txt'

with open(path,'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} #单词为key,出现频率为value的字典

for word in sorted(counts_dict, key=lambda x: counts_dict[x], reverse=True):
    print('{}--{} times'.format(word, counts_dict[word]))   # 打印整理后函数


知识点:

Mac用户使用open函数:

Open('/Users/DELL/Desktop/Walden.txt')

Windows用户使用open函数:

Open('C://Users/DELL/Desktop/Walden.txt')


列表:

 

列表解析方式放入元素(耗时短,效率高)

普通写法:

a = []
for i in range(1, 11):
    a.append(i)

列表解析:

a = [i for i in range(1,11)]

 

.lower()消除大写

.strip() 移除字符串头尾指定的字符(默认为空格)

 

sting模块一些有用的字符串常量

       string.digits:数字 0 - 9 的字符串

       string.letters:所有字母(大写和小写)的字符串

       string.lowercase:所有小写字母的字符串

       string.printable:所有可打印字符的字符串

       string.punctuation:所有标点的字符串

       string.uppercase:所有大写字母的字符串

 

Sorted()函数:按照长短、大小、英文字母顺序给列表中元素排序(Reverse:默认参数reverse可以使列表按逆序整理)

Sorted(num_list,reverse = true)

 

Key=lambda x:counts_dict[x]: lambda表达式,暂理解为以字典中的值为排序参数




















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值