Grok 4.1 Fast· xai
Frontier Reasoning Traces
Write a Python function to create a frequency dictionary from large text.
- User
Write a Python function to create a frequency dictionary from large text.
- Assistant
from collections import Counter import re def create_frequency_dict(text: str, by_words: bool = True) -> dict: """ Creates a frequency dictionary from large text. Args: text (str): The input text. by_words (bool): If True, counts word frequencies (lowercased, alphanumeric only). If False, counts character frequencies (lowercased). Returns: dict: Frequency dictionary {item: count}. Optimized for large text using efficient Counter and regex splitting. """ if by_words: # Extract words: lowercase, alphanumeric only (removes punctuation) words = re.findall(r'\w+', text.lower()) return dict(Counter(words)) else: # Character frequencies: lowercase only return dict(Counter(c.lower() for c in text if c.isalpha() or c.isdigit() or c.isspace()))Example Usage:
text = "Hello world! Hello, world. This is a test." freq = create_frequency_dict(text, by_words=True) print(freq) # {'hello': 2, 'world': 2, 'this': 1, 'is': 1, 'a': 1, 'test': 1} char_freq = create_frequency_dict(text, by_words=False) print(char_freq) # {'h': 2, 'e': 3, 'l': 4, ...}
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.