Comparing character frequencies between strings is a common task in text analysis, useful for detecting anagrams, identifying plagiarism, or simply analyzing letter distribution. Python's collections.Counter provides a high-level, efficient way to perform these comparisons without writing complex loops.
This guide explains how to use the Counter class to count elements, perform arithmetic operations on counts (like intersection and subtraction), and apply these techniques to practical problems.
Understanding collections.Counter
collections.Counter is a specialized dictionary subclass designed to count hashable objects. It takes an iterable (like a string or list) and creates a dictionary where keys are elements and values are their counts.
Basic Example:
from collections import Counter
text = "banana"
char_counts = Counter(text)
print(f"Counts: {char_counts}")
print(f"Most common: {char_counts.most_common(2)}")Output:
Counts: Counter({'a': 3, 'n': 2, 'b': 1})
Most common: [('a', 3), ('n', 2)]Comparing Counts (Intersection and Subtraction)
The Counter class supports arithmetic operations that make comparing two datasets intuitive.
- Intersection (
&): Returns the minimum count of elements found in both counters. - Subtraction (
-): Subtracts counts, keeping only positive results.
from collections import Counter
string1 = "apple"
string2 = "pear"
c1 = Counter(string1)
c2 = Counter(string2)
shared = c1 & c2
print(f"Shared characters: {shared}")
unique_to_s1 = c1 - c2
print(f"Unique to '{string1}': {unique_to_s1}")Output:
Shared characters: Counter({'a': 1, 'p': 1, 'e': 1})
Unique to 'apple': Counter({'p': 1, 'l': 1})Practical Example: Anagram Detection
Two strings are anagrams if they contain the exact same characters with the exact same frequencies. Using Counter, this check becomes a simple equality comparison.
from collections import Counter
def are_anagrams(str1, str2):
s1_clean = str1.replace(" ", "").lower()
s2_clean = str2.replace(" ", "").lower()
return Counter(s1_clean) == Counter(s2_clean)
word1 = "Listen"
word2 = "Silent"
word3 = "Apple"
print(f"'{word1}' and '{word2}' are anagrams? {are_anagrams(word1, word2)}")
print(f"'{word1}' and '{word3}' are anagrams? {are_anagrams(word1, word3)}")Output:
'Listen' and 'Silent' are anagrams? True
'Listen' and 'Apple' are anagrams? FalseAnalyzing Word Frequencies
While this guide focused on characters, Counter is equally effective for whole words. This is standard in Natural Language Processing (NLP).
from collections import Counter
sentence = "the quick brown fox jumps over the lazy dog"
word_counts = Counter(sentence.split())
print(f"Top words: {word_counts.most_common(2)}")Output:
Top words: [('the', 2), ('quick', 1)]Conclusion
Using collections.Counter simplifies frequency analysis significantly.
- Initialize with
Counter(iterable)to get counts instantly. - Compare using standard operators like
&(intersection) and-(difference). - Check Equality (
c1 == c2) to detect anagrams or identical datasets.