方法一:
#将文本内容转换为字典进行统计file01 = open('art.txt','r')list = file01.read().replace(',','').replace('.','').replace(';','').split() #读取文件去除文本中的特殊符号并切片list01 = {}for i in list: #生成字典,单词为keys,出现的次数为value if i in list01.keys(): list01[i] = list01[i] + 1 else: list01[i] = 1a = sorted(list01.items(), key=lambda va:va[1],reverse=True) #排序count = 0for j in a: if count <5: print('单词 %s 出现了 %d 次' % (j[0],j[1])) #打印前5名 count += 1 else: breakfile01.close()
方法二:
#将文本内容转换为列表进行统计from collections import Counterfile = open('art.txt','r')list01 = file.read().replace(',','').replace('.','').replace(';','').split() #读取文件去除文本中的特殊符号并切片a = Counter(list01) #排序b = a.most_common(5) #取出前5名for i in b: print('单词 %s 出现了 %d 次' % (i[0], i[1]))file01.close()
输出结果:
单词 the 出现了 6 次单词 of 出现了 5 次单词 in 出现了 3 次单词 to 出现了 3 次单词 something 出现了 3 次