统计文本出现的每个每个单词的次数,并列出频率最高的前五个单词
# coding=utf-8 from random import randint # 读取文本 with open('test.txt') as t: content=t.readlines() # print(content) # 对读取到的文本进行分词,以空位符为分割符 content[0:-1]=content[0].split() mapping=dict() # 将列表中的单词转化为小写 for s in content: words=[s.lower()] # 计算单词的个数并写入字典中 for word in words: mapping[word]=mapping.get(word,0)+1 # 对字典中的元素进行排序 mapping_list=sorted(mapping.items(),key=lambda i:i[1],reverse=True) # 输出出现频率最高的五个单词 print(mapping_list[0:5])
最后的结果:
[('and', 4), ('of', 4), ('the', 4), ('to', 3), ('semantic', 3)]