今天看到了一个关于文本词频统计的python代码。
import string path = '/home/ywq/Desktop/Walden.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) words_count = {index:words.count(index) for index in words_index} for word in sorted(words_count ,key=lambda x:words_count[x],reverse=True): print('{}--{} times'.format(word,words_count[word]))
用内置的string模块将文本中的标点符号和大写处理好,然后转换为set集合去掉重复项,创建一个词和频率的字典,最后排序输出。
使用的文本是瓦尔登湖