乐之之

知而行乐,乐而行之,天道酬勤,学无止境。
22、统计英文短文中前十个次数最多的单词

题目:

  在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)]

  

 

posted on 2022-11-07 12:24  乐之之  阅读(36)  评论(0编辑  收藏  举报