sort list by frequency

This question already has an answer here:

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

  • You've to use word_freq.items() here:

    lis = sorted(word_freq.items(), key = lambda x:x[1], reverse = True)
    for word,freq in lis:
        print ("%-10s %d" % (word, freq))
    

    Don't use list as a variable name.


    使用collections.Counter来帮助计算事物,并with语句来帮助打开(和关闭)文件。

    import collections
    
    with open('C:TempTest2.txt', 'r') as f:
        text = f.read()
    
    word_freq = collections.Counter(text.lower().split())
    for word, freq in word_freq.most_common():
        print ("%-10s %d" % (word, freq))
    

    看看collections.Counter

    >>> wordlist = ['foo', 'bar', 'foo', 'baz']
    >>> import collections
    >>> counter = collections.Counter(wordlist)
    >>> counter.most_common()
    [('foo', 2), ('baz', 1), ('bar', 1)]
    
    链接地址: http://www.djcxy.com/p/18158.html

    上一篇: Python:通过值将字典与元组进行排序

    下一篇: 按频率排序