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]是匿名函数表达式。