Sorted Word frequency count using python

前端 未结 10 939
再見小時候
再見小時候 2020-11-28 06:00

I have to count the word frequency in a text using python. I thought of keeping words in a dictionary and having a count for each of these words.

Now if I have to so

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 06:39

    You can use the same dictionary:

    >>> d = { "foo": 4, "bar": 2, "quux": 3 }
    >>> sorted(d.items(), key=lambda item: item[1])
    

    The second line prints:

    [('bar', 2), ('quux', 3), ('foo', 4)]
    

    If you only want a sorted word list, do:

    >>> [pair[0] for pair in sorted(d.items(), key=lambda item: item[1])]
    

    That line prints:

    ['bar', 'quux', 'foo']
    

提交回复
热议问题