PythonMastery

Word frequency counter in Python

Count how many times each word appears in a piece of text, using a dictionary. Also handles capital letters and punctuation, and shows Counter.

To count words, split the text into words and keep a dictionary where each key is a word and each value is how many times you have seen it.

The program

python
text = "The cat sat on the mat. The cat was happy, and the mat was warm."

counts = {}
for word in text.lower().split():
    word = word.strip(".,!?;:")
    counts[word] = counts.get(word, 0) + 1

for word, n in counts.items():
    print(word, n)
output
the 4
cat 2
sat 1
on 1
mat 2
was 2
happy 1
and 1
warm 1

How it works

Another way: Counter

collections.Counter does the counting for you, and most_common(n) gives the n most frequent words, largest count first:

python
from collections import Counter

text = "The cat sat on the mat. The cat was happy, and the mat was warm."
words = [w.strip(".,!?;:") for w in text.lower().split()]

for word, n in Counter(words).most_common(3):
    print(word, n)
output
the 4
cat 2
mat 2

When two words have the same count, most_common() keeps them in the order they were first seen.

Learn the idea: Dictionaries, Loops: for, while, and the Pythonic Patterns, Working with Strings

A longer explanation: Project: Word Frequency Counter