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

来源:互联网 发布:关于走心的文案 知乎 编辑:程序博客网 时间:2024/05/19 16:38

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表达式,暂理解为以字典中的值为排序参数




















原创粉丝点击