Matching¶
KeywordMatcher ¶
KeywordMatcher(keywords: KeywordsInput, match_type: str | MatchType = 'exact', threshold: float = 85, *, scorer: str | Scorer = 'ratio', min_fuzzy_length: int = 4, overlaps: str | Overlaps = 'longest', case_sensitive: bool = False, ignore_accents: bool = False, stemmer: str | Callable[[str], str] | None = None, unicode_form: str | None = 'NFKC', acronym_case: str = 'strict', context_scope: str = 'sentence')
Bases: BaseMatcher
Find keywords (and their synonyms, acronyms, variants and patterns) in text.
Example::
matcher = KeywordMatcher(["machine learning", Keyword("United States", acronyms="US")])
matcher.find("ML in the U.S.") # -> [Match(...)]
matcher.match(text, "count") # -> {"machine learning": 0, ...}
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keywords
|
KeywordsInput
|
A :class: |
required |
match_type
|
str | MatchType
|
|
'exact'
|
threshold
|
float
|
Minimum fuzzy similarity (0-100). |
85
|
scorer
|
str | Scorer
|
RapidFuzz scorer name ( |
'ratio'
|
min_fuzzy_length
|
int
|
Terms shorter than this are never fuzzy-matched. |
4
|
overlaps
|
str | Overlaps
|
|
'longest'
|
case_sensitive
|
bool
|
Default for terms that don't set it (acronyms are case-sensitive anyway). |
False
|
ignore_accents
|
bool
|
Treat |
False
|
stemmer
|
str | Callable[[str], str] | None
|
|
None
|
unicode_form
|
str | None
|
Unicode normalisation applied to text and terms before matching
( |
'NFKC'
|
acronym_case
|
str
|
How acronym-like terms ( |
'strict'
|
context_scope
|
str
|
Where |
'sentence'
|
configure ¶
configure(**options: Any) -> KeywordMatcher
Change options in place: matcher.configure(threshold=80, stemmer="light").
Assigning the attributes directly works too; either way the index is rebuilt on the next call. Invalid values raise and leave the matcher unchanged.
options ¶
options() -> dict[str, Any]
The current options (KeywordMatcher(keywords, **matcher.options()) makes a twin).
compile ¶
compile(force: bool = False) -> KeywordMatcher
(Re)build the index. Called automatically when the keywords or the options change.
Thread-safe: concurrent find calls always see one complete, consistent index.
find ¶
find(text: str) -> list[Match]
Return all keyword matches in text, sorted by position.
Offsets and :attr:Match.text always refer to the original text, whatever
normalisation was applied. The index is (re)built first if the keywords or options changed.
Raises:
| Type | Description |
|---|---|
TypeError
|
|
ExactMatcher ¶
ExactMatcher(keywords: KeywordsInput, **kwargs: Any)
Bases: KeywordMatcher
:class:KeywordMatcher with match_type="exact".
Accepts the same keyword arguments as :class:KeywordMatcher.
FuzzyMatcher ¶
FuzzyMatcher(keywords: KeywordsInput, threshold: float = 85, **kwargs: Any)
Bases: KeywordMatcher
:class:KeywordMatcher with match_type="fuzzy" (exact + typo-tolerant).
Accepts the same keyword arguments as :class:KeywordMatcher; threshold (0-100, default
85) is the minimum similarity for a fuzzy match.
BaseMatcher ¶
Bases: ABC
Subclass and implement :meth:find (and keyword_list) to build a custom matcher.
find
abstractmethod
¶
find(text: str) -> list[Match]
Return all matches in text, sorted by position.
match ¶
match(text: str, output: Literal['matches', MATCHES] = ...) -> list[Match]
match(text: str, output: Literal['detailed', DETAILED]) -> list[dict[str, Any]]
match(text: str, output: Literal['keywords', KEYWORDS]) -> list[str]
match(text: str, output: Literal['boolean', BOOLEAN]) -> dict[str, bool]
match(text: str, output: Literal['count', COUNT]) -> dict[str, int]
match(text: str, output: Literal['categories', CATEGORIES]) -> dict[str | None, int]
match(text: str, output: Literal['score', SCORE]) -> float
match(text: str, output: str | OutputFormat) -> Any
match(text: str, output: str | OutputFormat = MATCHES) -> Any
Match text and return the result in the requested output format.
Formats: "matches" (list of :class:Match, default), "detailed" (list of dicts),
"keywords" (unique names, in order of appearance), "boolean" / "count"
(dict over all keywords), "categories" (counts per category), "score" (float).
match_many ¶
match_many(texts: Iterable[str], output: Literal['matches', MATCHES] = ...) -> Iterator[list[Match]]
match_many(texts: Iterable[str], output: Literal['keywords', KEYWORDS]) -> Iterator[list[str]]
match_many(texts: Iterable[str], output: Literal['count', COUNT]) -> Iterator[dict[str, int]]
match_many(texts: Iterable[str], output: Literal['score', SCORE]) -> Iterator[float]
match_many(texts: Iterable[str], output: str | OutputFormat) -> Iterator[Any]
match_many(texts: Iterable[str], output: str | OutputFormat = MATCHES) -> Iterator[Any]
Lazily match many texts: for result in matcher.match_many(docs, "keywords"): ...
The output format is validated immediately, not on the first iteration.
format_output ¶
format_output(matches: list[Match], output: str | OutputFormat) -> Any
Convert matches (e.g. from :meth:find) to an output format (see :meth:match).
score ¶
score(text: str) -> float
Sum of matched keyword weights (fuzzy matches are scaled by their score).
Match
dataclass
¶
Match(keyword: str, start: int, end: int, text: str, term: str, kind: str = 'keyword', method: str = 'exact', score: float = 100.0, category: str | None = None, keyword_obj: Keyword | None = None)
A single keyword occurrence in a text.
Attributes:
| Name | Type | Description |
|---|---|---|
keyword |
str
|
Canonical keyword name. |
start, |
end
|
Character offsets into the original text ( |
text |
str
|
The surface text that matched, exactly as it appears in the document. |
term |
str
|
The configured term that produced the match (e.g. the synonym |
kind |
str
|
|
method |
str
|
|
score |
float
|
Similarity in |
category |
str | None
|
The keyword's category, if any. |
keyword_obj |
Keyword | None
|
The :class: |
weight
property
¶
weight: float
The matched keyword's :attr:~keylex.Keyword.weight (1.0 if unknown).
overlaps ¶
overlaps(other: Match) -> bool
True if this match shares at least one character with other.
sort_key ¶
sort_key() -> tuple[int, int, str]
Position order: by start, longer first, then keyword name (sorted(ms, key=Match.sort_key)).
to_dict ¶
to_dict() -> dict[str, Any]
JSON-compatible dict of the match (without keyword_obj); score is rounded to 2 places.
highlight ¶
Render matches inside the original text.
highlight ¶
highlight(text: str, matches: Iterable[Match], style: str | Callable[[Match], str] = 'brackets', *, escape: bool | None = None) -> str
Return text with every match wrapped according to style.
style is a preset name ("brackets", "labels", "markdown", "ansi",
"html"), a format string using {text}, {keyword}, {term}, {category},
{score}, or a callable Match -> str. Overlapping matches are rendered once (the
earliest/longest wins).
escape HTML-escapes the document text (inside and between matches) and the values filled
into the template. None (default) escapes when the template looks like HTML, i.e. contains
"<" (so the "html" preset and templates such as "<mark>{text}</mark>"); callables are
escaped only with escape=True, in which case they receive a copy of each :class:Match whose
text, keyword, term and category are already escaped.
OutputFormat ¶
Bases: _ValuesEnum
What :meth:KeywordMatcher.match returns.
Overlaps ¶
Bases: _ValuesEnum
How overlapping matches of different spans are resolved.
MatchType ¶
Bases: _ValuesEnum
How :class:KeywordMatcher searches: exact only, or exact plus typo-tolerant.