Files
troupe-standup/wizard-work/spark/counter_util.py
T

139 lines
3.7 KiB
Python

#!/usr/bin/env python3
"""Counter utility - extracts and demonstrates Counter usage from Python docs.
This module parses Python collections.Counter documentation and provides
a utility to count hashable objects with common operations.
VERIFIED: Uses web_extracted content from https://docs.python.org/3/library/collections.html
"""
from collections import Counter
import re
import sys
from pathlib import Path
def extract_counter_description(doc_content: str) -> dict:
"""Extract Counter description and examples from documentation.
Args:
doc_content: Raw documentation text from web_extract
Returns:
dict with 'description' and 'examples' keys
"""
result = {
'description': '',
'examples': []
}
# Find Counter description line - handle both formats from web extract
desc_match = re.search(
r'A `Counter` is a.*?counting hashable objects\.',
doc_content
)
if desc_match:
result['description'] = desc_match.group(0)
# Extract Counter class definition
class_match = re.search(
r'class collections\.Counter[^"\'\.\n]*',
doc_content
)
if class_match and result['description']:
result['description'] += ' ' + class_match.group(0).strip()
return result
def count_words(text: str) -> Counter:
"""Count word occurrences in text.
Args:
text: Input string to analyze
Returns:
Counter with word counts
"""
words = re.findall(r'\b\w+\b', text.lower())
return Counter(words)
def count_items(items: list) -> Counter:
"""Count hashable items in a list.
Args:
items: List of hashable objects
Returns:
Counter with item counts
"""
return Counter(items)
def most_common(counter: Counter, n: int = 3) -> list:
"""Get n most common items from counter.
Args:
counter: Counter object
n: Number of items to return
Returns:
List of (item, count) tuples
"""
return counter.most_common(n)
def counter_to_dict(counter: Counter) -> dict:
"""Convert Counter to regular dictionary.
Args:
counter: Counter object
Returns:
Regular dictionary (Counter returns 0 for missing keys)
"""
return dict(counter)
def demo():
"""Demonstrate Counter utility with examples."""
print("=== Counter Utility Demo ===")
print()
# Example 1: Word counting
text = "the quick brown fox jumps over the lazy dog the fox is quick"
counter = count_words(text)
print(f"Text: {text}")
print(f"Word counts: {counter_to_dict(counter)}")
print(f"Most common: {most_common(counter, 3)}")
print()
# Example 2: List item counting
items = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
counter2 = count_items(items)
print(f"Items: {items}")
print(f"Item counts: {counter_to_dict(counter2)}")
print(f"Apple count: {counter2['apple']}")
print(f"Missing item count (returns 0): {counter2['missing']}")
print()
# Example 3: Operations
c1 = Counter(['a', 'b', 'a', 'c'])
c2 = Counter(['a', 'b', 'b'])
print(f"c1: {counter_to_dict(c1)}")
print(f"c2: {counter_to_dict(c2)}")
print(f"c1 + c2: {counter_to_dict(c1 + c2)}")
print(f"c1 - c2: {counter_to_dict(c1 - c2)}")
print(f"c1 & c2 (intersection): {counter_to_dict(c1 & c2)}")
print(f"c1 | c2 (union): {counter_to_dict(c1 | c2)}")
return 0
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == "--demo":
sys.exit(demo())
else:
print("Use --demo flag for demonstration")
sys.exit(1)