fo=open('test.txt','r') a=fo.read() exc={'the','a','to','of','and','in','that','on',''} a=a.lower() for i in ',.': a=a.replace(i,' ') words=a.split(' ') print(words) dic={} keys=set(words) keys=keys-exc print (keys) for i in keys: dic[i]=words.count(i) print(dic) wc=list(dic.items()) wc.sort(key=lambda x:x[1],reverse=True) print(dic) for i in range(20): print(wc[i]) fo.close()
运行结果: