Count Word Frequency in Python with dict

Count how often each word appears in a text using Python's collections.Counter and regular expressions.

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

Python code

13 lines
Python 3.9+
from collections import Counter
import re

def count_word_frequency(text):
    """Count frequency of each word in text (case-insensitive)."""
    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!"
    word_counts = count_word_frequency(sample_text)
    for word, count in sorted(word_counts.items()):
        print(f"{word}: {count}")

Output

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

How it works

The re.findall(r"\b\w+\b", text.lower()) call splits the lowercase text into individual words, ignoring punctuation and case. Counter then builds a dictionary mapping each word to its frequency. Wrapping the Counter in dict() gives you a plain dictionary, which is useful for further processing. The sorted call in the loop ensures output appears in alphabetical order.

Common mistakes

  • Forgetting to call `.lower()` on the text, which makes 'The' and 'the' count separately.
  • Using `split()` instead of a regex, which leaves punctuation like 'dog.' attached to words.
  • Assuming Counter returns a regular dict when you need standard dict methods like `.get()`.

Variations

  1. Use `text.lower().split()` for a quick ap­proach when punctuation is not present.

Real-world use cases

  • Building a tag cloud or keyword tracker from user comments or articles.
  • Analyzing chat logs or support tickets to see which terms appear most often.
  • Preprocessing text before a machine-learning model to create a bag-of-words feature set.

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.