1 #CalHamletV1.py
2 def getText(): #定义函数读取文件
3 txt = open("hamlet.txt","r").read()4 txt = txt.lower() #将所有字符转换为小写
5 for ch in '!@#$%^&*(_)-+=\\[]}{|;:\'\"`~,<.>?/':6 txt = txt.replace(ch, " ") #将所有特殊符号用空格替代
7 returntxt8 hamletTxt =getText()9 words = hamletTxt.split() #用空格分隔文本并生成列表
10 counts ={}11 for word inwords:12 counts[word]=counts.get(word,0)+1 #生成字典的内容:若该键存在则取其值并+1
13 items=list(counts.items()) #返回所有键值对信息,生成列表
14 items.sort(key=lambda x:x[1],reverse=True) #对列表反排序:降序排列
15 for i in range(10):16 word, count =items[i]17 print("{0:<10}{1:>5}".format(word, count)) #打印前十个元素
18
19 #print(items[:10])
#结果如下: