Home / Python / Example programs / Strings

Python program: Count word frequency

Find the most common words in a piece of text.

The code

from collections import Counter

text = """It was the best of times, it was the worst of times,
it was the age of wisdom, it was the age of foolishness"""

words = text.lower().replace(",", "").split()
counts = Counter(words)
for word, n in counts.most_common(5):
    print(f"{word:<8}{n}")

Output

it      4
was     4
the     4
of      4
times   2

How it works

Lower-case and remove punctuation so "It" and "it" count as the same word, split into words, then Counter counts and ranks them. This is the first step of most text analysis.

Python features used

Learn the ideas behind it in the free lesson Modules & the Standard Library.