How to sort the output of a word count

This question already has an answer here:

  • How do I sort a dictionary by value? 38 answers

  • Simply use Counter. It will both shorten your code and get you the ordering that you want.

    Quoting from the documentation:

    A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

    >>> c = Counter(['eggs', 'ham'])
    >>> c['bacon']                              # count of a missing element is zero
    0
    

    You can view the sorted dictionary using operator.itemgetter() :

    from operator import itemgetter
    
    wordcount = {'test': 1, 'hello': 3, 'test2':0}
    
    sortedWords = sorted(wordcount.items(), key=itemgetter(1), reverse = True)
    

    Output:

    >>> sortedWords
    [('hello', 3), ('test', 1), ('test2', 0)]
    

    这应该为你做: -

    ally = open("alice.txt", "r")
    wordcount={}
    for word in ally.read().split():
        if word not in wordcount:
            wordcount[word] = 1
        else:
           wordcount[word] += 1
    
    for k,v, in sorted(wordcount.items(), key=lambda words: words[1], reverse = True):
        print(k,v)
    
    链接地址: http://www.djcxy.com/p/18166.html

    上一篇: 按值排序字典而不丢失密钥信息

    下一篇: 如何排序字数的输出