Skip to content

Keywords

Keyword

Keyword(keyword: str, synonyms: str | Iterable[str] | None = None, acronyms: str | Iterable[str] | None = None, *, variants: str | Iterable[str] | None = None, patterns: str | Iterable[str] | None = None, case_sensitive: bool | None = None, fuzzy: bool | None = None, exclude: str | Iterable[str] | None = None, require: str | Iterable[str] | None = None, context_window: int = 10, category: str | None = None, tags: str | Iterable[str] | None = None, weight: float = 1.0, metadata: Mapping[str, Any] | None = None)

A canonical keyword plus everything that should count as a mention of it.

Example::

ai = Keyword(
    "artificial intelligence",
    synonyms=["machine intelligence"],
    acronyms=["AI"],                       # case-sensitive: won't match "ai" in "Thai"
    exclude=["Steven Spielberg"],          # reject matches with this nearby
    category="technology",
)

Parameters:

Name Type Description Default
keyword str

The canonical name. Matches always report this name.

required
synonyms str | Iterable[str] | None

Alternative names (case-insensitive by default). A string or a list.

None
acronyms str | Iterable[str] | None

Abbreviations such as "AI" (case-sensitive by default; "US" also matches "U.S."). A string or a list.

None
variants str | Iterable[str] | None

Spellings and inflections ("colour"). A string or a list.

None
patterns str | Iterable[str] | None

Regular expressions that also count as this keyword.

None
case_sensitive bool | None

Default case sensitivity for this keyword's terms (None = inherit).

None
fuzzy bool | None

Whether fuzzy matching is allowed for this keyword (None = inherit).

None
exclude str | Iterable[str] | None

Context phrases; a match is rejected if one appears within context_window words of it (e.g. Keyword("Apple", exclude=["fruit", "pie"])).

None
require str | Iterable[str] | None

Context phrases; a match is kept only if at least one appears nearby.

None
context_window int

Number of words on each side inspected for exclude / require.

10
category str | None

Optional category, reported on every match.

None
tags str | Iterable[str] | None

Free-form labels (usable from rules via tag("...")).

None
weight float

Importance used by output="score" and rule scoring.

1.0
metadata Mapping[str, Any] | None

Arbitrary JSON-serialisable data carried along (IDs, codes, ...).

None

exclude property writable

exclude: list[str]

Context phrases that veto a match when found within :attr:context_window words of it.

Example: Keyword("Apple", exclude=["fruit", "pie"]). Assigning replaces the list.

require property writable

require: list[str]

Context phrases of which at least one must appear within :attr:context_window words.

An empty list means no requirement. Assigning replaces the list.

context_window property writable

context_window: int

Words inspected on each side of a match for :attr:exclude / :attr:require (default 10).

category property writable

category: str | None

Optional category, reported as :attr:Match.category and usable via CATEGORY(...) rules.

tags property writable

tags: list[str]

Free-form labels (a copy), usable via TAG(...) rules. Assigning replaces them all.

weight property writable

weight: float

Importance of the keyword (default 1.0), summed by output="score".

name property

name: str

The canonical keyword name, reported as :attr:Match.keyword on every match.

Read-only, so that :class:KeywordList indexes stay consistent; use :meth:KeywordList.rename or :meth:renamed to change it.

terms property

terms: list[Term]

All terms, canonical keyword first, in insertion order.

synonyms property writable

synonyms: list[str]

Alternative names (a copy). Assigning a string or list replaces them all.

has_synonyms property

has_synonyms: bool

True if the keyword has at least one synonym.

acronyms property writable

acronyms: list[str]

Abbreviations such as "AI" (a copy). Assigning a string or list replaces them all.

Acronyms are case-sensitive unless configured otherwise, and "US" also matches "U.S.".

has_acronyms property

has_acronyms: bool

True if the keyword has at least one acronym.

variants property writable

variants: list[str]

Spellings and inflections such as "colour" (a copy). Assigning replaces them all.

patterns property writable

patterns: list[str]

Regular expressions that also count as this keyword (a copy). Assigning replaces them all.

related_terms property writable

related_terms: list[str]

Synonyms, acronyms and variants (everything except the keyword and patterns).

has_related_terms: bool

True if the keyword has any synonym, acronym or variant.

case_sensitive property writable

case_sensitive: bool | None

Default case sensitivity for this keyword's terms; None inherits from the matcher.

Precedence: a term's own setting, then this, then the acronym rule (all-caps terms are case-sensitive), then the matcher's case_sensitive.

fuzzy property writable

fuzzy: bool | None

Whether fuzzy matching may be used for this keyword; None uses the default.

Only applies when the matcher uses match_type="fuzzy". Acronyms, patterns and terms shorter than min_fuzzy_length are never fuzzy-matched unless a term sets fuzzy.

renamed

renamed(new_name: str) -> Keyword

Return a copy of this keyword with a different canonical name.

iter_terms

iter_terms(*kinds: str) -> Iterator[Term]

Iterate over the keyword's terms, optionally only those of the given kinds.

Example: kw.iter_terms("synonym", "acronym"). Iterates over a snapshot, so adding terms while iterating is safe.

add_terms

add_terms(kind: TermKind, *items: str | Term | Iterable[str | Term] | None) -> None

Add terms of the given kind. Duplicates (case-insensitive) are ignored.

remove_terms

remove_terms(kind: TermKind, *items: str | Iterable[str] | None) -> None

Remove terms of the given kind (case-insensitive; patterns by exact text).

Terms that are not present are ignored.

clear_terms

clear_terms(*kinds: str) -> None

Remove every term of the given kinds; with no arguments, all terms except the keyword.

add_synonyms

add_synonyms(*synonyms: str | Iterable[str] | None) -> None

Add synonyms: add_synonyms("a", "b") or add_synonyms(["a", "b"]).

remove_synonyms

remove_synonyms(*synonyms: str | Iterable[str] | None) -> None

Remove synonyms (case-insensitive); missing ones are ignored.

set_synonyms

set_synonyms(*synonyms: str | Iterable[str] | None) -> None

Replace all synonyms with the given ones.

clear_synonyms

clear_synonyms() -> None

Remove all synonyms.

add_acronyms

add_acronyms(*acronyms: str | Iterable[str] | None) -> None

Add acronyms: add_acronyms("AI", "A.I.") or add_acronyms(["AI"]).

remove_acronyms

remove_acronyms(*acronyms: str | Iterable[str] | None) -> None

Remove acronyms (case-insensitive); missing ones are ignored.

set_acronyms

set_acronyms(*acronyms: str | Iterable[str] | None) -> None

Replace all acronyms with the given ones.

clear_acronyms

clear_acronyms() -> None

Remove all acronyms.

add_variants

add_variants(*variants: str | Iterable[str] | None) -> None

Add spelling variants: add_variants("colour", "colours") or a list.

remove_variants

remove_variants(*variants: str | Iterable[str] | None) -> None

Remove variants (case-insensitive); missing ones are ignored.

add_patterns

add_patterns(*patterns: str | Iterable[str] | None) -> None

Add regular expressions, e.g. add_patterns(r"GPT-\d+").

Raises:

Type Description
ValueError

a pattern is not a valid regular expression.

remove_patterns

remove_patterns(*patterns: str | Iterable[str] | None) -> None

Remove patterns (exact text match); missing ones are ignored.

add_related_terms(synonyms: str | Iterable[str] | None = None, acronyms: str | Iterable[str] | None = None, variants: str | Iterable[str] | None = None) -> None

Add synonyms, acronyms and variants in one call.

remove_related_terms(synonyms: str | Iterable[str] | None = None, acronyms: str | Iterable[str] | None = None, variants: str | Iterable[str] | None = None) -> None

Remove synonyms, acronyms and variants in one call; missing ones are ignored.

clear_related_terms() -> None

Remove all synonyms, acronyms and variants (patterns are kept).

copy

copy() -> Keyword

Return an independent deep copy (changes to it never affect this keyword).

to_dict

to_dict() -> dict[str, Any]

Serialise to a JSON-compatible dict (inverse of :meth:from_dict).

from_dict classmethod

from_dict(data: Mapping[str, Any]) -> Keyword

Build a keyword from :meth:to_dict output (unknown keys raise ValueError).

Term dataclass

Term(text: str, kind: TermKind = 'keyword', case_sensitive: bool | None = None, fuzzy: bool | None = None, whole_word: bool = True)

One surface form of a keyword.

Parameters:

Name Type Description Default
text str

The text to match (or a regular expression when kind="pattern").

required
kind TermKind

"keyword", "synonym", "acronym", "variant" or "pattern".

'keyword'
case_sensitive bool | None

None inherits from the keyword / matcher. Acronyms and all-caps terms such as "NASA" are case-sensitive by default.

None
fuzzy bool | None

Allow fuzzy matching for this term. None = default (acronyms, patterns and very short terms are never fuzzy-matched).

None
whole_word bool

Only match on word boundaries (default). False allows matches inside words, e.g. "bio" in "biotech".

True

is_acronym_like property

is_acronym_like: bool

True for acronyms and short all-caps terms ("NASA", "G7").

Such terms are case-sensitive and never fuzzy-matched unless configured otherwise.

to_dict

to_dict() -> dict[str, Any]

Serialise to a JSON-compatible dict; options left at their default are omitted.

from_dict classmethod

from_dict(data: Mapping[str, Any]) -> Term

Build a term from :meth:to_dict output (unknown keys are ignored).

KeywordList

KeywordList(keywords: Iterable[KeywordLike] | None = None, *, on_duplicate: OnDuplicate = 'merge')

An ordered collection of :class:Keyword objects with unique names.

Example::

kl = KeywordList(["python", "rust"])
kl.add(Keyword("artificial intelligence", acronyms="AI"))
kl.save("keywords.json"); KeywordList.load("keywords.json")

Parameters:

Name Type Description Default
keywords Iterable[KeywordLike] | None

Keywords, plain strings, or keyword dicts.

None
on_duplicate OnDuplicate

What to do when a keyword with an existing name is added: "merge" (default, combine terms), "skip", "replace" or "error".

'merge'

keywords property

keywords: list[Keyword]

The keywords as a list (a copy; mutate the list through its methods).

names property

names: list[str]

Canonical keyword names, in insertion order.

from_list classmethod

from_list(keywords: Iterable[KeywordLike], **kwargs: Any) -> KeywordList

Build from strings, :class:Keyword objects and/or keyword dicts.

from_dict classmethod

from_dict(data: Mapping[str, Any], **kwargs: Any) -> KeywordList

Build from a dict. Accepts every format keylex produces or documents:

  • to_dict() output: {"AI": {"synonyms": [...], "acronyms": [...], ...}}
  • shorthand: {"AI": ["machine intelligence", {"acronyms": ["AI"]}]}
  • simple: {"AI": "machine intelligence"} / {"AI": None}
  • versioned JSON document: {"version": 1, "keywords": [...]}

from_json classmethod

from_json(data: str, **kwargs: Any) -> KeywordList

Parse a JSON string: a list of keywords, or any dict accepted by :meth:from_dict.

Reads the output of :meth:to_json.

from_csv classmethod

from_csv(data: str, **kwargs: Any) -> KeywordList

Parse CSV with a keyword column and optional synonyms, acronyms, variants, patterns, exclude, require, tags (; or | separated, or a JSON array), category, weight, case_sensitive, fuzzy and context_window columns. Output of :meth:to_csv round-trips losslessly.

from_text classmethod

from_text(data: str, **kwargs: Any) -> KeywordList

One keyword per line; optional synonyms after |.

# starts a comment at the start of a line or after whitespace, so C# and F# are keywords, not comments. Example line: artificial intelligence | machine intelligence | AI

load classmethod

load(path: str | Path, **kwargs: Any) -> KeywordList

Load from .json, .csv, .yaml/.yml (needs PyYAML) or .txt.

Files are read as UTF-8; UTF-8/16/32 byte-order marks are detected automatically.

to_dict

to_dict() -> dict[str, dict[str, Any]]

{name: {"synonyms": [...], "acronyms": [...], ...}} -- round-trips via :meth:from_dict.

to_list

to_list() -> list[dict[str, Any]]

A list of keyword dicts (each includes the "keyword" key).

to_json

to_json(indent: int | None = 2) -> str

Versioned JSON document; read back with :meth:from_json.

to_csv

to_csv() -> str

CSV with one row per keyword; round-trips through :meth:from_csv without loss.

to_yaml

to_yaml() -> str

YAML document (a list of keyword dicts); needs PyYAML. Round-trips via :meth:load.

to_text

to_text() -> str

The plain-text format: keyword | synonym | synonym, one keyword per line.

The format only holds names and synonyms. Raises ValueError if a keyword has anything else (acronyms, options, ...) that would be lost; use JSON, CSV or YAML for those.

save

save(path: str | Path) -> None

Save as .json, .csv, .yaml/.yml or .txt depending on the file extension.

The file is written atomically: a failure never leaves a truncated file behind.

add

add(keyword: KeywordLike, *, on_duplicate: OnDuplicate | None = None) -> Keyword

Add a keyword (object, string or dict). Returns the keyword stored in the list.

extend

extend(keywords: Iterable[KeywordLike]) -> None

Add several keywords, applying the list's on_duplicate policy to each.

remove

remove(keyword: Keyword | str) -> Keyword

Remove by name (or by a keyword with that name). Raises KeyError if missing.

discard

discard(keyword: Keyword | str) -> None

Remove a keyword by name (or by a keyword with that name) if present; never raises.

rename

rename(old: str, new: str) -> Keyword

Rename a keyword in place, keeping its position and all of its terms.

clear

clear() -> None

Remove all keywords.

merge

merge(other: KeywordList | Iterable[KeywordLike]) -> KeywordList

Merge another list into this one (copies, never shares objects). Returns self.

copy

copy() -> KeywordList

Deep copy: the new list holds copies of the keywords, not the same objects.

get

get(name: str, default: Keyword | None = None) -> Keyword | None

Get by name; falls back to a case-insensitive lookup.

find_term

find_term(text: str) -> list[Keyword]

Keywords that have text as their name or one of their terms (case-insensitive).

find_conflicts

find_conflicts() -> dict[str, list[str]]

Surface forms shared by more than one keyword, {form: [keyword names]}.

Names that differ only in case ("Bank" / "bank") and synonyms reused across keywords both show up here. Such keywords all match the same text, which is fine when they are meant to be told apart by context rules, and usually a mistake otherwise.

categories

categories() -> dict[str | None, list[Keyword]]

Group keywords by category: {category: [keywords]} (None for uncategorised).

filter

filter(predicate: Callable[[Keyword], bool] | None = None, *, category: str | None = None, tag: str | None = None) -> KeywordList

A new list (sharing the same keyword objects) with the keywords that pass all filters.

signature

signature() -> tuple[int, int, tuple[int, ...]]

Changes whenever the list or any keyword in it changes (used for cache invalidation).