← Back to all snippets
PYTHON

Perform Frequency Counting and Analysis with collections.Counter

Quickly count object occurrences and perform frequency analysis in Python using the highly optimized collections.Counter data structure for efficient data insights.

from collections import Counter

def analyze_word_frequency(text):
    """
    Analyzes word frequency in a given text string.
    Returns a Counter object and common words.
    """
    if not isinstance(text, str):
        raise TypeError("Input must be a string.")

    # Basic tokenization: convert to lowercase and split by non-alphanumeric
    # A more robust solution might use regex or NLTK
    words = [word.lower() for word in text.split() if word.isalpha()]
    
    word_counts = Counter(words)
    
    # Get the 3 most common words
    most_common = word_counts.most_common(3)
    
    return word_counts, most_common

def analyze_list_frequency(data_list):
    """
    Analyzes frequency of items in a list.
    """
    if not isinstance(data_list, list):
        raise TypeError("Input must be a list.")
        
    item_counts = Counter(data_list)
    return item_counts

# Example usage:
sample_text = "Python is great. Python is powerful. Python is versatile. Python Python Python."
word_freq, common_words = analyze_word_frequency(sample_text)
# print(f"Word Frequencies: {word_freq}")
# print(f"Most Common Words: {common_words}") # Expected: [('python', 6), ('is', 3), ('great', 1)]

sample_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple', 'grape']
list_freq = analyze_list_frequency(sample_list)
# print(f"List Item Frequencies: {list_freq}") # Expected: Counter({'apple': 3, 'banana': 2, 'orange': 1, 'grape': 1})
How it works: This snippet demonstrates `collections.Counter`, a specialized dictionary subclass for counting hashable objects. It efficiently tallies occurrences of items in a list or characters/words in a string, providing methods like `most_common()` to easily retrieve the elements with the highest frequencies. This data structure is invaluable for frequency analysis, vote counting, or any scenario where you need to quickly determine the distribution of elements within a collection.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs