统计文档中出现次数最多的单词

本地的一个txt文档中保存着若干个英文单词,每行一个单词,输出出现次数最多的单词(不区分英文大小写)

import collections

with  open('string','r') as f:
    list = []
    for line in f:
        word = line.strip().lower()
        #去掉末尾的\n;统一转换为小写字母
        list.append(word)
    key_v = collections.Counter(list)
    print(key_v)
    most = key_v.most_common(1)
    print(most[0][0],most[0][1])#出现最多的单词和相应的数量

#P.s.

#可用字符串存储:
with  open('string','r') as f:
    string = ''
    for line in f:
        string += line.lower()
    key_v = collections.Counter(string.split())#按空格隔开的字符进行计数

collections模块方法:

https://www.cnblogs.com/dianel/p/10787693.html
https://www.cnblogs.com/keke-xiaoxiami/p/8553076.html

用lambda嵌套方式计算最大数量:

    max_k = max(dict(key_v),key = lambda x :dict(key_v)[x])
    max_v = dict(key_v)[max_k]
    print(max_k,max_v)

lambda用法:
https://www.cnblogs.com/caizhao/p/7905094.html

    原文作者:爷开始做美梦
    原文地址: https://blog.csdn.net/youhuidier/article/details/104527491
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞