Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
24 lines
713 B
Python
24 lines
713 B
Python
"""Word counting and truncation."""
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
def count_words(text: str) -> int:
|
|
"""Number of whitespace separated words in ``text``."""
|
|
return len(text.split())
|
|
|
|
|
|
def truncate_words(text: str, limit: int, suffix: str = "...") -> str:
|
|
"""Keep the first ``limit`` words of ``text``.
|
|
|
|
If words were dropped, ``suffix`` is appended directly after the last kept
|
|
word. Text with ``limit`` words or fewer is returned with normalised
|
|
spacing and no suffix.
|
|
"""
|
|
if limit < 1:
|
|
raise ValueError("limit must be at least 1")
|
|
words = text.split()
|
|
if len(words) <= limit:
|
|
return " ".join(words)
|
|
return " ".join(words[:limit - 1]) + suffix
|