Skip to content
GreenSnippets

Count word frequency in text

Tokenize text and list the most common words using collections.Counter.

Python
import re
from collections import Counter

WORD = re.compile(r"[\w']+", re.UNICODE)


def top_words(text, n=10):
    words = (w.lower() for w in WORD.findall(text))
    return Counter(words).most_common(n)

Example / expected output

Output
top_words("the cat and the hat", 2)  # [('the', 2), ('cat', 1)]

How it works

Counter does the counting and most_common(n) returns the top entries. The regular expression keeps letters and apostrophes, and lower-casing treats "The" and "the" as one word. Real language processing needs more care (stop words, stemming, non-Latin scripts), but this covers most quick analyses.