"""Word statistics.""" from __future__ import annotations import re from typing import Dict, List, Tuple def word_frequencies(text: str) -> Dict[str, int]: """Count lower-cased words (letters, digits and apostrophes only).""" counts: Dict[str, int] = {} for word in re.findall(r"[A-Za-z0-9']+", text.lower()): counts[word] = counts.get(word, 0) + 1 return counts def top_words(text: str, n: int = 3) -> List[Tuple[str, int]]: """The ``n`` most frequent words; ties are ordered alphabetically.""" counts = word_frequencies(text) ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0])) return ranked[:n]