Count Word Frequency in Python with dict
Count how often each word appears in a text using Python's collections.Counter and regular expressions.
Python code
13 linesfrom 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
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
- Use `text.lower().split()` for a quick approach 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
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.