Skip to content

Rules

Rule engine: combine keyword matches into higher-level conditions.

__all__ module-attribute

__all__ = ['AllOf', 'AnyOf', 'AtLeast', 'CategoryRule', 'Document', 'EngineResult', 'KeywordRule', 'NamedRule', 'Near', 'Not', 'Rule', 'RuleEngine', 'RuleResult', 'RuleSyntaxError', 'SameParagraph', 'SameSentence', 'TagRule', 'all_of', 'any_of', 'at_least', 'before', 'category', 'kw', 'near', 'none_of', 'not_', 'parse_rule', 'same_paragraph', 'same_sentence', 'tag']

AllOf

AllOf(*rules: Rule | str)

Bases: Rule

All child rules match (AND). Occurrences: the smallest count of the positive children.

AnyOf

AnyOf(*rules: Rule | str, min_count: int = 1)

Bases: Rule

At least min_count of the child rules match (default 1 = OR).

With min_count > 1 only children satisfied by different matches count (see the module docs). Occurrences: for OR the number of distinct matches of the match-counting children plus the counts of the others; for min_count > 1 the min_count-th largest count among the distinct children.

AtLeast

AtLeast(rule: Rule | str, n: int)

Bases: Rule

The child rule occurs at least n times (see the module docs for what an occurrence is).

CategoryRule

CategoryRule(name: str)

Bases: Rule

Matches when any keyword of the given category (case-insensitive) occurs.

Document

Document(text: str, matches: Iterable[Match], *, aliases: Mapping[str, str] | None = None)

A text plus its matches, with lazily computed token / sentence / paragraph positions.

Sub-rule results are cached per document (see :meth:evaluate), so a sub-rule shared by several rules of a :class:~keylex.rules.RuleEngine is evaluated once per text.

Parameters:

Name Type Description Default
text str

The text the matches were found in.

required
matches Iterable[Match]

The keyword matches.

required
aliases Mapping[str, str] | None

Optional {term: keyword name} map; a keyword rule naming term matches the keyword (used by :class:~keylex.rules.RuleEngine for rules naming a synonym/acronym).

None

restrict

restrict(matches: Iterable[Match]) -> Document

A view of this document that only contains matches (positions are shared).

evaluate

evaluate(rule: Rule) -> RuleResult

Evaluate rule on this document, reusing the result of structurally equal rules.

keyword_matches

keyword_matches(name: str) -> list[Match]

Matches of the keyword name (case-insensitive; aliases resolved).

word_index

word_index(char_pos: int) -> int

Index of the word token containing / preceding char_pos.

word_span

word_span(m: Match) -> tuple[int, int]

(first, last) word indices covered by a match.

unit_count

unit_count(unit: str) -> int

Number of sentences (unit="sentence") or paragraphs in the text.

unit_of

unit_of(m: Match, unit: str) -> int

Index of the sentence (unit="sentence") or paragraph that a match starts in.

sentence_of

sentence_of(m: Match) -> int

Index of the sentence that a match starts in.

paragraph_of

paragraph_of(m: Match) -> int

Index of the paragraph that a match starts in.

KeywordRule

KeywordRule(name: str)

Bases: Rule

Matches when the keyword (canonical name, case-insensitive) occurs.

Near

Near(a: Rule | str, b: Rule | str, within: int = 5, ordered: bool = False)

Bases: Rule

Two rules match within within words of each other (ordered: a before b).

With ordered=True (BEFORE) the a match must end before the b match starts (no overlap). Matches with identical spans never pair up. Occurrences: the number of disjoint qualifying pairs, formed greedily left to right (each match takes part in at most one pair).

Not

Not(rule: Rule | str)

Bases: Rule

Negation. Never contributes matches.

At the top level (or inside AND / OR) it means "nowhere in the text". As an operand of :class:SameSentence / :class:SameParagraph it means "not in that sentence / paragraph". It is rejected as an operand of NEAR, BEFORE and ATLEAST.

Rule

Bases: ABC

Base class. Combine rules with & (and), | (or), ~ (not).

Subclasses implement :meth:evaluate and :meth:to_dsl. Composite rules should evaluate their children with doc.evaluate(child) so results are cached per document.

evaluate abstractmethod

evaluate(doc: Document) -> RuleResult

Evaluate the rule on doc. Call doc.evaluate(rule) instead to use the cache.

to_dsl abstractmethod

to_dsl() -> str

Serialise to the rule language accepted by :func:parse_rule.

keyword_names

keyword_names() -> set[str]

Keyword names referenced by this rule (auto-added by :class:RuleEngine).

children

children() -> Sequence[Rule]

Direct sub-rules (empty for leaf rules such as keywords).

label

label() -> str

Short label used for nested nodes in :meth:RuleResult.explain.

test

test(text: str, matcher: BaseMatcher) -> RuleResult

Convenience: run matcher.find(text) and evaluate this rule.

at_least

at_least(n: int) -> AtLeast

This rule occurring at least n times: kw("bank").at_least(3).

RuleResult dataclass

RuleResult(rule: Rule, matched: bool, matches: tuple[Match, ...] = (), children: tuple[RuleResult, ...] = (), detail: str = '', count: int | None = None)

Outcome of evaluating a rule; truthy when the rule matched.

count is the number of occurrences of the rule (see the module docs); when a custom rule leaves it unset, :attr:occurrences falls back to the number of distinct matched spans.

occurrences property

occurrences: int

How many times the rule occurs (what ATLEAST counts); 0 when it did not match.

keywords property

keywords: list[str]

Unique names of the keywords behind :attr:matches, in order of appearance.

explain

explain(indent: int = 0, *, full_label: bool = True) -> str

Human-readable tree showing why the rule did or didn't match.

The top node shows the whole rule; nested nodes show a short label (operator plus a truncated form) so the output grows linearly with the size of the rule.

SameParagraph

SameParagraph(*rules: Rule | str)

Bases: _SameUnit

All rules match inside one paragraph (blocks separated by blank lines).

SameSentence

SameSentence(*rules: Rule | str)

Bases: _SameUnit

All rules match inside one sentence (NOT x operands: x is not in that sentence).

TagRule

TagRule(name: str)

Bases: Rule

Matches when any keyword carrying the tag (case-insensitive) occurs.

RuleSyntaxError

RuleSyntaxError(message: str, source: str, pos: int, rule_name: str | None = None, filename: str | None = None)

Bases: ValueError

Raised for malformed rule strings; the message points at the offending position.

Attributes:

Name Type Description
message

The bare error message (without position / pointer).

source

The rule string.

pos

Character offset of the problem in source.

rule_name

Name of the rule being loaded, when known (prefixed to the message).

filename

The rules file the rule came from, when known (prefixed to the message).

with_rule_name

with_rule_name(name: str) -> RuleSyntaxError

A copy of this error whose message names the rule it came from.

with_filename

with_filename(filename: str) -> RuleSyntaxError

A copy of this error whose message names the file it came from.

EngineResult dataclass

EngineResult(text: str, matches: list[Match], results: dict[str, RuleResult], rules: dict[str, NamedRule])

Result of :meth:RuleEngine.evaluate.

"name" in result tells whether a rule fired; result["name"] is its :class:RuleResult.

Attributes:

Name Type Description
text str

The evaluated text.

matches list[Match]

All keyword matches found in the text.

results dict[str, RuleResult]

{rule name: RuleResult} for every rule, fired or not.

rules dict[str, NamedRule]

The engine's rules at evaluation time.

fired property

fired: list[str]

Names of the rules that matched, highest weight first.

score property

score: float

Sum of the weights of the rules that matched.

top property

top: str | None

The highest-weight rule that matched (handy for single-label classification).

explain

explain() -> str

ASCII tree per rule (top node: the whole rule; nested nodes: short labels).

to_dict

to_dict() -> dict[str, Any]

JSON-compatible summary: fired rules, score, and per-rule details with their matches.

NamedRule dataclass

NamedRule(name: str, rule: Rule, weight: float = 1.0, description: str = '', source: str = '')

A rule registered in a :class:RuleEngine with its name, weight and description.

to_dict

to_dict() -> dict[str, Any]

{"rule": <rule string>, "weight": ..., "description": ...} (defaults omitted).

RuleEngine

RuleEngine(keywords: KeywordsInput | None = None, rules: Mapping[str, Rule | str | Mapping[str, Any]] | None = None, **matcher_options: Any)

Evaluate a set of named, weighted rules against texts.

Keywords referenced by rules but missing from keywords are added automatically as plain keywords, so the quickest start is just::

engine = RuleEngine(rules={
    "finance": 'bank AND NOT NEAR(bank, river, 5)',
    "ai": 'ANY("machine learning", "neural network", AI)',
})
engine.evaluate(text).fired

A rule name that is not a keyword name but a synonym / acronym / variant of exactly one keyword (e.g. ML for "machine learning") refers to that keyword. If several keywords share the term, a warning is issued and the term is matched as a keyword of its own.

Parameters:

Name Type Description Default
keywords KeywordsInput | None

Keyword definitions (synonyms, acronyms, categories, ...). Optional.

None
rules Mapping[str, Rule | str | Mapping[str, Any]] | None

{name: rule} where a rule is a :class:Rule, a rule string, or a dict {"rule": ..., "weight": 2.0, "description": "..."}. Weights must be finite numbers; negative weights act as penalties in :attr:EngineResult.score.

None
**matcher_options Any

Passed to :class:KeywordMatcher (match_type, threshold, stemmer, overlaps, ...). Overlaps default to "all" here so that rules can see nested keywords (e.g. both "interest rate" and "rate").

{}

rules property

rules: dict[str, NamedRule]

{name: NamedRule} (a copy; change rules with :meth:add_rule / :meth:remove_rule).

matcher property

matcher: KeywordMatcher

The underlying matcher (user keywords + keywords referenced by rules).

add_rule

add_rule(name: str, rule: Rule | str, weight: float = 1.0, description: str = '') -> RuleEngine

Add (or replace) a named rule. Returns self for chaining.

Raises:

Type Description
RuleSyntaxError

the rule string is malformed (the message names the rule).

ValueError

empty name or non-finite weight.

remove_rule

remove_rule(name: str) -> None

Remove the rule called name. Raises KeyError if there is none.

evaluate

evaluate(text: str) -> EngineResult

Match text once and evaluate every rule (shared sub-rules are evaluated once).

evaluate_many

evaluate_many(texts: Iterable[str]) -> Iterator[EngineResult]

Lazily :meth:evaluate each text.

classify

classify(text: str) -> list[str]

Names of the rules that fire, highest weight first.

score

score(text: str) -> float

Sum of the weights of the rules that fire on text.

validate

validate() -> list[str]

Static checks of the rule set; returns human-readable messages (empty list = clean).

The messages of :meth:diagnostics, errors and warnings alike.

diagnostics

diagnostics() -> list[tuple[str, str]]

Static checks of the rule set as (level, message) pairs.

"error" (the rule set is broken): no rules at all, CATEGORY / TAG names that no keyword has, ANY(n, ...) with fewer than n operands, non-finite weights.

"warning" (informational; keylex rules --check passes unless --strict): rules naming keywords that are not in the keyword list (only when a keyword list was given; they are added automatically, which is the intended use without one), names that are a term of several keywords, and a lower-case and / or between bare words (rock and roll means rock AND roll).

to_dict

to_dict() -> dict[str, Any]

{"rules": ..., "keywords": ..., "options": ...}, readable by :meth:from_dict.

Only JSON-serialisable matcher options are kept (a callable stemmer is dropped).

from_dict classmethod

from_dict(data: Mapping[str, Any] | None, **matcher_options: Any) -> RuleEngine

Inverse of :meth:to_dict: {"keywords": [...], "rules": {...}, "options": {...}}.

Raises:

Type Description
ValueError

a malformed structure (the message says what is wrong).

load classmethod

load(path: str | Path, **matcher_options: Any) -> RuleEngine

Load a JSON (or YAML, with PyYAML) rules file (UTF-8; a byte-order mark is ignored).

Raises:

Type Description
OSError

the file cannot be read.

ValueError

malformed content (the message names the file); rule syntax errors are :class:RuleSyntaxError naming the rule.

ImportError

a YAML file but PyYAML is not installed.

save

save(path: str | Path) -> None

Write :meth:to_dict as JSON; atomic, so a failure never truncates an existing file.

all_of

all_of(*rules: Rule | str) -> AllOf

All of rules match (AND). DSL: ALL(a, b, ...) or a AND b. Strings are keyword names.

any_of

any_of(*rules: Rule | str, min_count: int = 1) -> AnyOf

At least min_count of rules match (default 1: OR). DSL: ANY(n, a, b, ...).

With min_count > 1 operands must be satisfied by different matches, so any_of("ML", "machine learning", min_count=2) does not fire on a single "ML". Strings are keyword names.

at_least

at_least(n: int, rule: Rule | str) -> AtLeast

rule occurs at least n times. DSL: ATLEAST(n, rule).

See the module docs for what counts as an occurrence of each kind of rule.

before

before(a: Rule | str, b: Rule | str, within: int = 5) -> Near

a occurs before b with at most within words in between. DSL: BEFORE(a, b, within).

category

category(name: str) -> CategoryRule

Any keyword of category name occurs (case-insensitive). DSL: CATEGORY(name).

kw

kw(*names: str) -> Rule

kw("bank"); several names mean any of them: kw("bank", "lender").

near

near(a: Rule | str, b: Rule | str, within: int = 5, ordered: bool = False) -> Near

a and b occur with at most within words between them. DSL: NEAR(a, b, within).

Parameters:

Name Type Description Default
a Rule | str

A rule or keyword name.

required
b Rule | str

A rule or keyword name.

required
within int

Maximum number of words between the two matches.

5
ordered bool

Require a before b (the same as :func:before).

False

none_of

none_of(*rules: Rule | str) -> Not

None of rules occurs anywhere in the text. DSL: NONE(a, b, ...).

not_

not_(rule: Rule | str) -> Not

rule does not match (same as ~rule). DSL: NOT rule.

same_paragraph

same_paragraph(*rules: Rule | str) -> SameParagraph

All rules match inside one paragraph (blocks separated by blank lines). DSL: PARAGRAPH(a, b, ...).

same_sentence

same_sentence(*rules: Rule | str) -> SameSentence

All rules match inside one sentence. DSL: SENTENCE(a, b, ...).

A not_(x) operand means x is absent from that sentence.

tag

tag(name: str) -> TagRule

Any keyword tagged name occurs (case-insensitive). DSL: TAG(name).

parse_rule

parse_rule(source: str) -> Rule

Parse a rule string into a :class:Rule; parse_rule(rule.to_dsl()) == rule.