Skip to content

Keyword extraction

Unsupervised keyword extraction: find the important keywords of a text without a keyword list.

Quick use::

from keylex import extract_keywords
extract_keywords(article, top_n=5)                 # YAKE by default
extract_keywords(article, method="rake")

Every extractor returns :class:ExtractedKeyword objects and can hand its results straight to the matching side via extractor.to_keyword_list(text).

RakeExtractor

RakeExtractor(top_n: int | None = 10, *, max_ngram: int = 4, **kwargs: Any)

Bases: BaseExtractor

RAKE (Rose et al., 2010): phrases are runs of non-stopwords; words are scored by degree / frequency. Favours longer, specific phrases.

Takes the :class:BaseExtractor arguments; max_ngram defaults to 4 here.

TextRankExtractor

TextRankExtractor(top_n: int | None = 10, *, window: int = 3, damping: float = 0.85, iterations: int = 50, **kwargs: Any)

Bases: BaseExtractor

TextRank (Mihalcea & Tarau, 2004): PageRank over a word co-occurrence graph.

Parameters:

Name Type Description Default
window int

Co-occurrence window (in content words).

3
damping float

PageRank damping factor.

0.85
iterations int

Maximum number of PageRank iterations (stops earlier once converged).

50

TfidfExtractor

TfidfExtractor(top_n: int | None = 10, *, corpus: Iterable[str] | None = None, **kwargs: Any)

Bases: BaseExtractor

TF-IDF over candidate phrases.

Call :meth:fit with a corpus (an iterable of documents) to learn document frequencies; terms that are common across the corpus then drop in the ranking. Without fitting, the sentences of the input text serve as pseudo-documents. Term frequency is sublinear (1 + log(count)), multi-word phrases get a small length bonus, and ties are broken by first occurrence.

Parameters:

Name Type Description Default
corpus Iterable[str] | None

Optional documents to :meth:fit on right away.

None

is_fitted property

is_fitted: bool

True once :meth:fit has learned document frequencies from a corpus.

fit

fit(corpus: Iterable[str]) -> TfidfExtractor

Learn document frequencies from a corpus (a non-empty iterable of strings). Returns self.

YakeExtractor

YakeExtractor(top_n: int | None = 10, *, window: int = 2, **kwargs: Any)

Bases: BaseExtractor

YAKE! (Campos et al., 2020): statistical features of a single document.

Considers casing, position, frequency, context diversity and sentence spread. Works well on short and long documents without any training data. This is the default extractor.

Parameters:

Name Type Description Default
window int

Co-occurrence window used for the context-diversity feature.

2

BaseExtractor

BaseExtractor(top_n: int | None = DEFAULT_TOP_N, *, max_ngram: int = 3, stopwords: Iterable[str] | None = None, language: str = 'en', min_word_length: int = 2, deduplicate: bool = True, dedup_threshold: float = 90, diversity: float = 0.3, pos_filter: Callable[[str], Any] | None = None)

Bases: ABC

Base class for extractors.

Parameters:

Name Type Description Default
top_n int | None

How many keywords :meth:extract returns by default (a positive integer; None means :data:DEFAULT_TOP_N).

DEFAULT_TOP_N
max_ngram int

Longest phrase (in words) to consider. Runs of capitalised words (names such as "ECB President Christine Lagarde") may be longer, up to :data:MAX_NAME_LENGTH words.

3
stopwords Iterable[str] | None

Iterable of stopwords; overrides language.

None
language str

Built-in stopword list to use ("en" default, "de", "fr", "es", "it", "el"). English also enables the verb heuristics.

'en'
min_word_length int

Shorter words are treated as stopwords (all-caps acronyms excepted).

2
deduplicate bool

Drop near-duplicates of better-ranked phrases (plurals, "e-mail"/"email", typos, shorter phrases that only occur inside a longer one).

True
dedup_threshold float

Similarity (0-100) above which two phrases are duplicates.

90
diversity float

Maximal Marginal Relevance trade-off in [0, 1]: 0 returns the plain ranking, higher values prefer phrases that share fewer words with those already selected ("Apple iPhone" vs "Apple iPhone sales"). Results are still returned best score first.

0.3
pos_filter Callable[[str], Any] | None

Optional spaCy Language with a tagger (e.g. spacy.load("en_core_web_sm")) or any callable text -> tokens with .idx, .text and .pos_. Only noun-phrase-shaped candidates (adjectives/nouns ending in a noun) are kept.

None

prepare

prepare(text: str) -> PreparedText

Tokenise text with this extractor's settings (stopwords, language, POS filter).

extract

extract(text: str, top_n: int | None = None) -> list[ExtractedKeyword]

Return the top_n best keywords/keyphrases of text, best first.

top_n=None uses the extractor's default; anything but a positive integer raises ValueError.

extract_many

extract_many(texts: Iterable[str], top_n: int | None = None) -> Iterator[list[ExtractedKeyword]]

Lazily :meth:extract the keywords of each text.

to_keyword_list

to_keyword_list(text: str, top_n: int | None = None) -> KeywordList

Extract and wrap the results in a :class:KeywordList ready for matching.

Every phrase is a surface form of text, so KeywordMatcher(kl).find(text) finds it again.

ExtractedKeyword dataclass

ExtractedKeyword(phrase: str, score: float, count: int = 1, positions: tuple[int, ...] = ())

A keyword found by an extractor.

Attributes:

Name Type Description
phrase str

The keyword as it appears in the text (most frequent spelling).

score float

Relevance normalised to (0, 1]; the best keyword scores 1.0.

count int

Number of occurrences in the text.

positions tuple[int, ...]

Character offsets where the occurrences start.

to_keyword

to_keyword(**kwargs: object) -> Keyword

A :class:~keylex.Keyword for :attr:phrase; kwargs go to the Keyword constructor.

to_dict

to_dict() -> dict[str, object]

{"phrase", "score", "count"} (score rounded to 4 places).

get_extractor

get_extractor(method: str = 'yake', **kwargs: Any) -> BaseExtractor

Instantiate an extractor by name ("yake", "rake", "textrank", "tfidf").

extract_keywords

extract_keywords(text: str, top_n: int | None = 10, method: str = 'yake', **kwargs: Any) -> list[ExtractedKeyword]

Extract the top_n most important keywords/keyphrases from text.