Text utilities¶
Text utilities shared by matchers, rules and extractors.
Everything here is dependency-free and works on plain str objects. Character offsets always
refer to the original text, so matches can be mapped back exactly.
Token
dataclass
¶
Token(text: str, start: int, end: int)
OffsetMap ¶
OffsetMap(starts: list[int], ends: list[int])
Maps character offsets in a normalised string back to the original string.
span ¶
span(start: int, end: int) -> tuple[int, int]
Original (start, end) for a span of the normalised text.
TokenNormalizer ¶
TokenNormalizer(ignore_accents: bool = False, stemmer: Callable[[str], str] | None = None)
Normalises a single token for case-insensitive comparison.
Applies casefold and, optionally, accent folding and a stemmer.
exact ¶
exact(token: str) -> str
Case-preserving normalisation (used for case-sensitive comparisons).
tokenize ¶
tokenize(text: str) -> list[Token]
Split text into word tokens (\w+) and single punctuation tokens.
fold_accents_with_offsets ¶
fold_accents_with_offsets(text: str) -> tuple[str, OffsetMap | None]
:func:fold_accents plus a map from the folded string back to text offsets.
light_stem ¶
light_stem(word: str) -> str
A conservative English plural stemmer (an extended S-stemmer).
It only removes plural endings, so it is safe to apply to both the text and the keywords::
banks -> bank, policies -> policy, boxes -> box, classes -> class, analysis -> analysis
movies -> movie, news -> news, crises -> crisis
resolve_stemmer ¶
resolve_stemmer(stemmer: str | Callable[[str], str] | None) -> Callable[[str], str] | None
Turn a stemmer name ("light") or callable into a callable (or None).
looks_like_acronym ¶
looks_like_acronym(text: str) -> bool
True for short all-caps tokens such as "US", "NASA", "G7".
normalize_text ¶
normalize_text(text: str, form: str | None = 'NFKC') -> tuple[str, OffsetMap | None]
Unicode-normalise text and return a map back to the original offsets.
Besides form normalisation, invisible format characters (soft hyphens, joiners, variation
selectors) are removed, zero-width spaces become spaces and typographic apostrophes become '.
Returns (text, None) when nothing changes (the common case, checked cheaply). Characters
are normalised in clusters (a character plus everything that combines with it), so every
cluster maps to exactly one span of the original text.
sentence_spans ¶
sentence_spans(text: str) -> list[tuple[int, int]]
Approximate sentence boundaries as (start, end) character spans.
Periods after common abbreviations ("Dr.", "U.S.", "e.g.") and initials ("J. Smith") do not end a sentence. Blank lines always end a sentence.
paragraph_spans ¶
paragraph_spans(text: str) -> list[tuple[int, int]]
Paragraph boundaries (blocks separated by blank lines) as (start, end) spans.