Python练习题第十题
题目:
从磁盘上读入一个英文文章,统计文章中每个单词出现的次数,并将频率最高的20个单词在屏幕上显示出来。
#2019/12/26/18:24
def getText():
txt=open(r'D:\第十题.txt').read()
#打开文件
txt=txt.lower()#将字母全部转化为小写
for ch in ',-.()':#去掉特殊符号
txt=txt.replace(ch,"")#将特殊符号替换为空格
return txt
Txt=getText()#读取文件
words=Txt.split()#分隔开
counts={}#创建字典
for word in words:
counts[word]=counts.get(word,0)+1
items=list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)
#从大到小排序
for i in range (20):
print(items[i])