Count word frequency in Python with dict and Counter

Count how often each word appears in a string using Counter, converted to a plain dict, and print results alphabetically.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 12 views 0 copies

Python code

12 lines
Python 3.9+
from collections import Counter
import re

def count_word_frequency(text):
    words = re.findall(r'\b\w+\b', text.lower())
    return dict(Counter(words))

if __name__ == "__main__":
    sample_text = "The quick brown fox jumps over the lazy dog. The dog barks, and the fox runs."
    frequency = count_word_frequency(sample_text)
    for word, count in sorted(frequency.items()):
        print(f"{word}: {count}")

Output

stdout
and: 1
barks: 1
brown: 1
dog: 2
fox: 2
jumps: 1
lazy: 1
over: 1
quick: 1
runs: 1
the: 3

How it works

re.findall(r'\b\w+\b', text.lower()) extracts whole words (letters/digits) after lowercasing, so punctuation like periods and commas don't pollute the counts. Counter tallies each word's occurrences and its dict() conversion gives a standard dictionary keyed by word with count values. Sorting the items with sorted() ensures deterministic alphabetical output for display. The result is immutable-free and easy to reuse for further text analysis.

Common mistakes

  • Forgetting to lowercase the text, so 'The' and 'the' count separately
  • Using `split()` on whitespace, which leaves punctuation attached to words like 'dog.'
  • Assuming `Counter` itself can be subscripted exactly like a dict (it can, but converting to dict avoids confusion)

Variations

  1. Use `text.lower().split()` if punctuation is already stripped from the text
  2. Return the `Counter` directly to allow `.most_common(n)` for top-N words

Real-world use cases

  • Generating word-frequency histograms for document analysis or search engines.
  • Analyzing customer feedback or support tickets to spot recurring keywords.
  • Building simple text summarization features that show dominant topics in an article.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.