spaCy integration¶
spaCy integration (pip install keylex[spacy]).
Add keylex as a pipeline component::
import spacy
import keylex.integrations.spacy # registers the "keylex" factory (also auto-registered via entry point)
nlp = spacy.blank("en")
nlp.add_pipe("keylex", config={"keywords": keyword_list.to_list(), "set_ents": True})
doc = nlp("Machine learning in the U.S.")
doc.spans["keylex"] # SpanGroup of matches, labelled by category (or keyword)
doc._.keylex_matches # all keylex Match objects (the matcher output)
span._.keylex_matches # every Match behind a span (identical spans of several keywords)
span._.keylex_match # the first of them
Matches are kept in doc.user_data as plain data, so processed docs survive doc.to_bytes(),
DocBin(store_user_data=True) and nlp.pipe(..., n_process=2); several keylex components add to
doc._.keylex_matches.
The component's keywords and options are saved with nlp.to_disk / nlp.to_bytes and restored
by spacy.load / nlp.from_bytes, including keywords given via :func:add_to_pipeline.
Or convert keywords into EntityRuler token patterns with :func:to_entity_ruler_patterns.
KeylexComponent ¶
KeylexComponent(nlp: Language, name: str, matcher: KeywordMatcher, spans_key: str = 'keylex', set_ents: bool = False, label: str = 'category', default_label: str = 'KEYWORD', *, overwrite_ents: bool = False, alignment_mode: str = 'strict', matcher_options: dict[str, Any] | None = None)
spaCy pipeline component that stores keylex matches on each Doc.
Usually created with nlp.add_pipe("keylex", config={...}) or :func:add_to_pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nlp
|
Language
|
The pipeline the component belongs to. |
required |
name
|
str
|
The component's name in the pipeline. |
required |
matcher
|
KeywordMatcher
|
The :class: |
required |
spans_key
|
str
|
|
'keylex'
|
set_ents
|
bool
|
Also add the matches to |
False
|
overwrite_ents
|
bool
|
With |
False
|
label
|
str
|
Span label: |
'category'
|
default_label
|
str
|
Label used by |
'KEYWORD'
|
alignment_mode
|
str
|
See :func: |
'strict'
|
matcher_options
|
dict[str, Any] | None
|
Extra :class: |
None
|
pipe ¶
pipe(docs: Iterable[Doc], batch_size: int = 128) -> Iterable[Doc]
Process a stream of docs (called by nlp.pipe).
set_keywords ¶
set_keywords(keywords: KeywordsInput, stemmer: str | Callable[[str], str] | None = None) -> None
Replace the keywords (a live :class:KeywordList stays live).
to_bytes ¶
to_bytes(*, exclude: Sequence[str] = ()) -> bytes
Serialise keywords and options (used by nlp.to_bytes).
from_bytes ¶
from_bytes(data: bytes, *, exclude: Sequence[str] = ()) -> KeylexComponent
Restore keywords and options from :meth:to_bytes output (used by nlp.from_bytes).
to_disk ¶
to_disk(path: str | Path, *, exclude: Sequence[str] = ()) -> None
Save keywords and options to path/keylex.json (used by nlp.to_disk).
from_disk ¶
from_disk(path: str | Path, *, exclude: Sequence[str] = ()) -> KeylexComponent
Load keywords and options saved by :meth:to_disk (used by spacy.load).
match_spans ¶
match_spans(doc: Doc, matcher: KeywordMatcher, label: str = 'category', default_label: str = 'KEYWORD', alignment_mode: str = 'strict') -> list[Span]
Run matcher over doc.text and return token-aligned :class:Span objects.
label: "category" (keyword category, falling back to default_label), "keyword"
(the canonical keyword name) or "fixed" (always default_label).
alignment_mode: "strict" (default) skips matches that don't start and end on token
boundaries (e.g. a whole_word=False term inside a word); "contract" / "expand"
shrink / grow them to whole tokens (spaCy's Doc.char_span modes).
Identical spans produced by several keywords appear once per label; span._.keylex_matches
lists every :class:Match behind a span.
make_keylex_component ¶
make_keylex_component(nlp: Language, name: str, keywords: Any, match_type: str, threshold: float, overlaps: str, stemmer: str | None, ignore_accents: bool, spans_key: str, set_ents: bool, overwrite_ents: bool, label: str, default_label: str, alignment_mode: str, matcher_options: dict[str, Any]) -> KeylexComponent
Factory: keywords may be a list of strings/keyword dicts, a dict, or a file path.
matcher_options holds any further :class:KeywordMatcher arguments (case_sensitive,
acronym_case, ...).
add_to_pipeline ¶
add_to_pipeline(nlp: Language, keywords: KeywordsInput, **config: Any) -> KeylexComponent
Convenience: add_to_pipeline(nlp, keyword_list, set_ents=True).
Unlike nlp.add_pipe("keylex", config=...) this accepts a live :class:KeywordList (or any
keyword input) directly. config keys are the factory's parameters plus name, before,
after, first, last; any other key (case_sensitive=True, a callable stemmer...)
is passed to the :class:KeywordMatcher. The keywords are saved with nlp.to_disk.
to_entity_ruler_patterns ¶
to_entity_ruler_patterns(keywords: KeywordsInput, label: str | Callable[[Any], str] = 'category', default_label: str = 'KEYWORD', *, nlp: Language | None = None, case_sensitive: bool = False) -> list[dict[str, Any]]
Token patterns for spaCy's EntityRuler (or SpanRuler).
Case-sensitive terms (acronyms such as NASA, or case_sensitive=True on the term/keyword,
else the case_sensitive default) use ORTH attributes, all others LOWER, so the ruler
agrees with :class:KeywordMatcher regardless of phrase_matcher_attr; acronyms also get their
dotted form ("US" -> spaCy's "U.S." token). label works as in :func:match_spans (any other
string is used as the label itself). Terms are tokenised
with nlp's tokenizer (default: spacy.blank("en")). Pattern id is the canonical keyword
name, so ent.ent_id_ tells you which keyword hit. Regex pattern terms cannot be expressed
and are skipped with a warning.