return the top n most frequently occurring chars and their respective counts in python

前端 未结 2 1200
我在风中等你
我在风中等你 2021-01-24 03:05

how to return the top n most frequently occurring chars and their respective counts # e.g \'aaaaaabbbbcccc\', 2 should return [(\'a\', 6), (\'b\'

2条回答
  •  一向
    一向 (楼主)
    2021-01-24 03:34

    A little harder, but also works:

    text = "abbbaaaa"
    
    dict = {}
    for lines in text:
        for char in lines:
            dict[char] = dict.get(char, 0) + 1
    
    print dict
    

提交回复
热议问题