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.
Python code
12 linesfrom 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
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
- Use `text.lower().split()` if punctuation is already stripped from the text
- 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
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.