题目:
在words_count.txt英文短文文件中,
找出前十个次数最多的单词。
思路:
1、创建一个新的空字典
2、遍历修饰所有单词,并逐个添加次数。
3、进行排序。
结果:
word_count= {}
with open("./words_count.txt",'r',encoding='utf-8') as f:
for line in f:
line = line[:-1]
words = line.split()
for word in words:
if word not in word_count:
word_count[word] = 0 # 相当于把每个出现的单词先写字典里遍,并附上次数为0
word_count[word] += 1
print(
sorted(word_count.items(),key=lambda x:x[1],reverse=True)[:-10]
--------------------------------------------------------------
[('we', 6), ('the', 4), ('of', 4), ('and', 4), ('hope', 3), ('In', 2), ('is', 2), ('It', 2), ('gives', 2), ('when', 2)]
标签:count,短文,word,22,中前,单词,次数,words,line From: https://www.cnblogs.com/LoLong/p/16865529.html