def read_file():
with open(‘C:/Users/84785/PycharmProjects/pythonProject/3.txt’, ‘r’, encoding=‘utf-8’) as f:
word = [] # 空列表用来存储文本中的单词
# readlins为分行读取文本,且返回的是一个列表,每行的数据作为列表中的一个元素:
for word_str in f.readlines():
# 去除原文中的逗号 双引号
word_str = word_str.replace(’,’, ‘’).replace(’"’, ‘’)
# strip去除每行字符串数据两边的空白字符
word_str = word_str.strip()
# 对单行字符串通过空格进行分割,返回一个列表
word_list = word_str.split(’ ')
# 将分割后的列表内容,添加到word空列表中
word.extend(word_list)
# 定义一个新字典存放单词以及数量
dic = {}
# 循环列表中的单词统计数量
for i in word:
count = word.count(i)
# 把数量设为字典的value值
dic[i] = count
# 使用sorted()方法对其排序sorted(iterable, key=None, reverse=False) iterable为可迭代的对象,使用items(
# )方法以列表返回可遍历的(键,值)元组数据,key为比较的元素
dic1 = sorted(dic.items(), key=lambda d: d[1], reverse=True)
print(dic1)
for i in range(5):
print(dic1[i])
read_file()