Sorted Word frequency count using python

前端 未结 10 935
再見小時候
再見小時候 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:22

    WARNING: This example requires Python 2.7 or higher.

    Python's built-in Counter object is exactly what you're looking for. Counting words is even the first example in the documentation:

    >>> # Tally occurrences of words in a list
    >>> from collections import Counter
    >>> cnt = Counter()
    >>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
    ...     cnt[word] += 1
    >>> cnt
    Counter({'blue': 3, 'red': 2, 'green': 1})
    

    As specified in the comments, Counter takes an iterable, so the above example is merely for illustration and is equivalent to:

    >>> mywords = ['red', 'blue', 'red', 'green', 'blue', 'blue']
    >>> cnt = Counter(mywords)
    >>> cnt
    Counter({'blue': 3, 'red': 2, 'green': 1})
    

提交回复
热议问题