Skip to content

pyroid.nltk

NLTK 3.10.4's Punkt sentence tokenizer and Treebank word tokenizers, with NLTK's API and results. Guide: pyroid.nltk.

NLTK 3.10.4's sentence and word tokenizers, in Rust.

import pyroid.nltk as nltk

nltk.sent_tokenize("Mr. Smith went to Washington. He liked it.")
# ['Mr. Smith went to Washington.', 'He liked it.']
nltk.word_tokenize("They'll pay $3.88 (roughly).")
# ['They', "'ll", 'pay', '$', '3.88', '(', 'roughly', ')', '.']
nltk.sent_tokenize(docs, language="german", threads=8)  # one list per document
nltk.TreebankWordDetokenizer().detokenize(["I", "ca", "n't", "go", "."])  # "I can't go."

sent_tokenize, word_tokenize, PunktSentenceTokenizer, PunktTokenizer, TreebankWordTokenizer, NLTKWordTokenizer, TreebankWordDetokenizer, align_tokens, wordpunct_tokenize, RegexpTokenizer (for common patterns), WhitespaceTokenizer and BlanklineTokenizer give NLTK 3.10.4's results, str for str and offset for offset. NLTK runs its patterns with the third-party regex module (nltk.redos) and, around them, Python's str methods; both are reproduced: regex 2026.9.29's character classes, and str.lower() / isupper() / islower() of the running CPython (3.11 to 3.15).

The Punkt models are NLTK's punkt_tab data, which pyroid does not bundle (it has no licence): install it with nltk.download('punkt_tab') or python -m nltk.downloader punkt_tab. With NLTK installed, the model is found and read by NLTK's own nltk.data.find and load_punkt_params (so nltk.data.path and its checks apply); without NLTK, pyroid looks in NLTK's default locations (NLTK_DATA, ~/nltk_data, sys.prefix's and the system's nltk_data directories) for tokenizers/punkt_tab/<language>/ or tokenizers/punkt_tab.zip. NLTK itself is not needed for anything else.

Handed to NLTK, with one pyroid.FallbackWarning per feature (pyroid.PyroidError if NLTK is not installed): training (PunktTrainer, PunktSentenceTokenizer(train_text)), a custom token_cls, a PunktLanguageVars subclass that changes more than sent_end_chars, parameters that are not sets of str, PunktSentenceTokenizer.dump, saving parameters, a Treebank tokenizer whose pattern lists were changed or overridden, and a RegexpTokenizer pattern that is not one of the native ones.

pyroid extensions: the tokenizers also take a list or tuple of str, or an Arrow string column, and return one list per document (None for an Arrow null), computed in parallel on pyroid's shared pool (threads=: None for the whole pool, n for at most n tasks, 1 for the calling thread).

Differences from NLTK:

  • Lone surrogates ("\ud800") raise UnicodeEncodeError, as everywhere in pyroid.
  • No pattern runs under NLTK's 5-second regex timeout, so nothing raises TimeoutError on very long inputs.
  • Results follow regex 2026.9.29's Unicode tables; with another regex release installed, NLTK can differ on characters whose properties changed between the two.
  • Looking up an unseen word in PunktParameters.ortho_context does not add a 0 entry to it (NLTK's defaultdict grows with every new word it tokenizes).
  • An NLTK PunktParameters given to a tokenizer is copied (into a pyroid PunktParameters, which tok._params returns); edit it through tok._params, since later edits of the NLTK object are not seen.
  • NLTK compiles a PunktLanguageVars object's patterns at first use, so it keeps using the old sent_end_chars in part of the algorithm after they are changed; pyroid uses the new ones throughout.

NLTK_VERSION module-attribute

NLTK_VERSION: Final[str]

The NLTK release whose tokenizers this module reproduces ("3.10.4").

REGEX_VERSION module-attribute

REGEX_VERSION: Final[str]

The regex release whose Unicode tables the patterns follow ("2026.9.29").

UNICODE_VERSION module-attribute

UNICODE_VERSION: Final[str]

This CPython's unicodedata.unidata_version, which str case tests follow.

DEBUG_DECISION_FMT module-attribute

DEBUG_DECISION_FMT: Final[str]

REASON_DEFAULT_DECISION module-attribute

REASON_DEFAULT_DECISION: Final[str]

REASON_KNOWN_COLLOCATION module-attribute

REASON_KNOWN_COLLOCATION: Final[str]

REASON_ABBR_WITH_ORTHOGRAPHIC_HEURISTIC module-attribute

REASON_ABBR_WITH_ORTHOGRAPHIC_HEURISTIC: Final[str]

REASON_ABBR_WITH_SENTENCE_STARTER module-attribute

REASON_ABBR_WITH_SENTENCE_STARTER: Final[str]

REASON_INITIAL_WITH_ORTHOGRAPHIC_HEURISTIC module-attribute

REASON_INITIAL_WITH_ORTHOGRAPHIC_HEURISTIC: Final[str]

REASON_NUMBER_WITH_ORTHOGRAPHIC_HEURISTIC module-attribute

REASON_NUMBER_WITH_ORTHOGRAPHIC_HEURISTIC: Final[str]

REASON_INITIAL_WITH_SPECIAL_ORTHOGRAPHIC_HEURISTIC module-attribute

REASON_INITIAL_WITH_SPECIAL_ORTHOGRAPHIC_HEURISTIC: Final[
    str
]

PunktParameters

PunktParameters()

Stores data used to perform sentence boundary detection with Punkt.

The attributes are NLTK's. Change them in place (params.abbrev_types.add("dr")) or assign new ones; tokenizers using these parameters see the change at their next call.

abbrev_types instance-attribute

abbrev_types: set[str]

Lowercase abbreviations, without their final period ("dr").

collocations instance-attribute

collocations: set[tuple[str, str]]

Word pairs whose first word ends in a period that is not a sentence break.

sent_starters instance-attribute

sent_starters: set[str]

Words that often start a sentence.

ortho_context instance-attribute

ortho_context: defaultdict[str, int]

Orthographic contexts (bit flags) each word type was seen in.

clear_abbrevs

clear_abbrevs() -> None

Replace abbrev_types with an empty set.

clear_collocations

clear_collocations() -> None

Replace collocations with an empty set.

clear_sent_starters

clear_sent_starters() -> None

Replace sent_starters with an empty set.

clear_ortho_context

clear_ortho_context() -> None

Replace ortho_context with an empty defaultdict(int).

add_ortho_context

add_ortho_context(typ: str, flag: int) -> None

Add flag to the orthographic contexts of typ.

PunktLanguageVars

NLTK's language-dependent variables of the Punkt algorithm.

Subclass it and change sent_end_chars (a tuple of one-character strings) to break sentences at other characters; that still runs in Rust. Overriding anything else (the patterns, word_tokenize) hands the tokenizer to NLTK, with a pyroid.FallbackWarning.

sent_end_chars instance-attribute

sent_end_chars: tuple[str, ...]

Characters which are candidates for sentence boundaries ((".", "?", "!")).

internal_punctuation instance-attribute

internal_punctuation: str

Sentence-internal punctuation (",:;"; used in training).

word_tokenize

word_tokenize(s: str) -> list[str]

Punkt's word tokenization of s (runs in NLTK).

period_context_re

period_context_re() -> Any

NLTK's compiled period-context pattern (from NLTK).

PunktSentenceTokenizer

PunktSentenceTokenizer(
    train_text: Any = None,
    verbose: bool = False,
    lang_vars: Any = None,
    token_cls: Any = ...,
)

NLTK's PunktSentenceTokenizer, running in Rust.

Parameters:

  • train_text (Any, default: None ) –

    Training text (trained with NLTK's PunktTrainer: a pyroid.FallbackWarning), or a PunktParameters (pyroid's or NLTK's) to use. None or empty: empty parameters.

  • verbose (bool, default: False ) –

    Passed to the trainer.

  • lang_vars (Any, default: None ) –

    A PunktLanguageVars (pyroid's or NLTK's).

  • token_cls (Any, default: ... ) –

    NLTK's PunktToken or a subclass; anything but the default runs in NLTK.

PUNCTUATION instance-attribute

PUNCTUATION: tuple[str, ...]

train

train(train_text: Any, verbose: bool = False) -> Any

Return parameters trained on train_text (with NLTK), or train_text if not a str.

tokenize

tokenize(
    text: str,
    realign_boundaries: bool = True,
    *,
    threads: int | None = None,
) -> list[str]
tokenize(
    text: _Batch,
    realign_boundaries: bool = True,
    *,
    threads: int | None = None,
) -> list[list[str]]
tokenize(
    text: ArrowStrings,
    realign_boundaries: bool = True,
    *,
    threads: int | None = None,
) -> list[list[str] | None]

Split text into sentences.

Parameters:

  • text (str | _Batch | ArrowStrings) –

    A str, or a batch as for sent_tokenize.

  • realign_boundaries (bool, default: True ) –

    Move closing quotes and brackets that follow a sentence break into the sentence they close.

  • threads (int | None, default: None ) –

    For a batch, as for sent_tokenize.

sentences_from_text

sentences_from_text(
    text: str,
    realign_boundaries: bool = True,
    *,
    threads: int | None = None,
) -> list[str]
sentences_from_text(
    text: _Batch,
    realign_boundaries: bool = True,
    *,
    threads: int | None = None,
) -> list[list[str]]
sentences_from_text(
    text: ArrowStrings,
    realign_boundaries: bool = True,
    *,
    threads: int | None = None,
) -> list[list[str] | None]

The same as tokenize.

span_tokenize

span_tokenize(
    text: str,
    realign_boundaries: bool = True,
    *,
    threads: int | None = None,
) -> Iterator[tuple[int, int]]
span_tokenize(
    text: _Batch,
    realign_boundaries: bool = True,
    *,
    threads: int | None = None,
) -> list[list[tuple[int, int]]]
span_tokenize(
    text: ArrowStrings,
    realign_boundaries: bool = True,
    *,
    threads: int | None = None,
) -> list[list[tuple[int, int]] | None]

The (start, end) offsets of the sentences in text.

A generator for a str, as NLTK's; for a batch, a list with one list of tuples per document. With realign_boundaries=False a span can be empty, as in NLTK.

tokenize_sents

tokenize_sents(
    strings: Sequence[str], *, threads: int | None = None
) -> list[list[str]]

tokenize of each string (in parallel).

span_tokenize_sents

span_tokenize_sents(
    strings: Sequence[str], *, threads: int | None = None
) -> Iterator[list[tuple[int, int]]]

span_tokenize of each string, as lists.

text_contains_sentbreak

text_contains_sentbreak(text: str) -> bool

Whether text contains a sentence break that is not at its last token.

sentences_from_text_legacy

sentences_from_text_legacy(text: str) -> Iterator[str]

The sentences of text, found by annotating every token (NLTK's older method).

sentences_from_tokens

sentences_from_tokens(
    tokens: Iterable[str],
) -> Iterator[list[str]]

Group word tokens into sentences (lists of the same tokens).

debug_decisions

debug_decisions(text: str) -> Iterator[dict[str, Any]]

One dict per candidate sentence break, with the evidence for the decision.

The keys and values are NLTK's (period_index is a code point offset); format one with format_debug_decision.

dump

dump(tokens: Any) -> str

NLTK's debugging dump of annotated tokens (runs in NLTK).

PunktTokenizer

PunktTokenizer(lang: str = 'english')

Bases: PunktSentenceTokenizer

A PunktSentenceTokenizer with the parameters of an installed punkt_tab model.

Parameters:

  • lang (str, default: 'english' ) –

    The model name ("english", "german", ...).

Raises:

  • TypeError –

    lang is not a str.

  • ValueError –

    lang cannot name one model.

  • LookupError –

    The model is not installed (nltk.download('punkt_tab')).

save_dir property

save_dir: str

NLTK's private directory for saved parameters (created by NLTK).

load_lang

load_lang(lang: str = 'english') -> None

Load the punkt_tab model for lang into this tokenizer.

save_params

save_params() -> str

Write the parameters as tab files under save_dir (with NLTK); return it.

MacIntyreContractions

List of contractions adapted from Robert MacIntyre's tokenizer (NLTK's).

CONTRACTIONS2 instance-attribute

CONTRACTIONS2: list[str]

CONTRACTIONS3 instance-attribute

CONTRACTIONS3: list[str]

CONTRACTIONS4 instance-attribute

CONTRACTIONS4: list[str]

TreebankWordTokenizer

Bases: _WordTokenizer

NLTK's TreebankWordTokenizer: the Penn Treebank tokenizer's rules, in Rust.

Splits contractions (don't -> do n't), most punctuation, and a period at the end of the text. Changing its pattern lists (on the class, a subclass or an instance) hands the call to NLTK with those patterns.

NLTKWordTokenizer

Bases: _WordTokenizer

NLTK's NLTKWordTokenizer, the improved Treebank rules word_tokenize uses.

It also splits Unicode quotes and guillemets, dashes, ellipses and some clitics.

TreebankWordDetokenizer

NLTK's TreebankWordDetokenizer: undo the Treebank tokenizer's padding, in Rust.

CONTRACTIONS2 instance-attribute

CONTRACTIONS2: Any

CONTRACTIONS3 instance-attribute

CONTRACTIONS3: Any

ENDING_QUOTES instance-attribute

ENDING_QUOTES: Any

DOUBLE_DASHES instance-attribute

DOUBLE_DASHES: Any

CONVERT_PARENTHESES instance-attribute

CONVERT_PARENTHESES: Any

PARENS_BRACKETS instance-attribute

PARENS_BRACKETS: Any

PUNCTUATION instance-attribute

PUNCTUATION: Any

STARTING_QUOTES instance-attribute

STARTING_QUOTES: Any

tokenize

tokenize(
    tokens: Sequence[str], convert_parentheses: bool = False
) -> str

Join tokens into text, undoing the tokenizer's padding.

Parameters:

  • tokens (Sequence[str]) –

    The tokens of one text.

  • convert_parentheses (bool, default: False ) –

    Replace PTB symbols (-LRB-, ...) with brackets.

detokenize

detokenize(
    tokens: Sequence[str], convert_parentheses: bool = False
) -> str

The same as tokenize.

RegexpTokenizer

RegexpTokenizer(
    pattern: Any,
    gaps: bool = False,
    discard_empty: bool = True,
    flags: int = ...,
)

NLTK's RegexpTokenizer: the matches of a pattern, or the text between them.

These patterns run in Rust when spelled exactly so and compiled with no flags beyond the default re.UNICODE | re.MULTILINE | re.DOTALL: \w+, \w+|[^\w\s]+, \w+|\$[\d\.]+|\S+, [\w']+, \S+, \s+, [a-zA-Z]+ and BlanklineTokenizer's. Any other pattern runs in NLTK, with one pyroid.FallbackWarning.

Parameters:

  • pattern (Any) –

    The pattern (a str, or a compiled pattern whose .pattern is used).

  • gaps (bool, default: False ) –

    The pattern matches the separators, not the tokens.

  • discard_empty (bool, default: True ) –

    With gaps, drop empty tokens.

  • flags (int, default: ... ) –

    The flags the pattern is compiled with.

tokenize

tokenize(
    text: str, *, threads: int | None = None
) -> list[str]
tokenize(
    text: _Batch, *, threads: int | None = None
) -> list[list[str]]
tokenize(
    text: ArrowStrings, *, threads: int | None = None
) -> list[list[str] | None]

The tokens of text; for a batch (as for sent_tokenize), one list per doc.

span_tokenize

span_tokenize(text: str) -> Iterator[tuple[int, int]]

The (start, end) offsets of the tokens in text (a generator, as NLTK's).

tokenize_sents

tokenize_sents(
    strings: Sequence[str], *, threads: int | None = None
) -> list[list[str]]

tokenize of each string (in parallel).

span_tokenize_sents

span_tokenize_sents(
    strings: Sequence[str],
) -> Iterator[list[tuple[int, int]]]

span_tokenize of each string, as lists.

WhitespaceTokenizer

WhitespaceTokenizer()

Bases: RegexpTokenizer

Split text at runs of whitespace (\s+ with gaps=True, regex's \s).

BlanklineTokenizer

BlanklineTokenizer()

Bases: RegexpTokenizer

Split text at blank lines (lines of nothing but whitespace).

WordPunctTokenizer

WordPunctTokenizer()

Bases: RegexpTokenizer

Split text into runs of word characters and of other non-space characters.

The pattern is \w+|[^\w\s]+.

sent_tokenize

sent_tokenize(
    text: str,
    language: str = "english",
    *,
    threads: int | None = None,
) -> list[str]
sent_tokenize(
    text: _Batch,
    language: str = "english",
    *,
    threads: int | None = None,
) -> list[list[str]]
sent_tokenize(
    text: ArrowStrings,
    language: str = "english",
    *,
    threads: int | None = None,
) -> list[list[str] | None]

Split text into sentences with the Punkt model for language (NLTK's sent_tokenize).

The tokenizer for each language is loaded once and kept, as in NLTK.

Parameters:

  • text (str | _Batch | ArrowStrings) –

    A str, or a list or tuple of str, or an Arrow string array or column.

  • language (str, default: 'english' ) –

    The punkt_tab model name ("english", "german", ...).

  • threads (int | None, default: None ) –

    For a batch: None uses the whole shared pool, n at most n tasks, 1 the calling thread.

Returns:

  • list[str] | list[list[str]] | list[list[str] | None] –

    The sentences; for a batch, one list per document (None for an Arrow null).

Raises:

word_tokenize

word_tokenize(
    text: str,
    language: str = "english",
    preserve_line: bool = False,
    *,
    threads: int | None = None,
) -> list[str]
word_tokenize(
    text: _Batch,
    language: str = "english",
    preserve_line: bool = False,
    *,
    threads: int | None = None,
) -> list[list[str]]
word_tokenize(
    text: ArrowStrings,
    language: str = "english",
    preserve_line: bool = False,
    *,
    threads: int | None = None,
) -> list[list[str] | None]

Split text into words (NLTK's word_tokenize).

The sentences of sent_tokenize, each split by NLTKWordTokenizer.

Parameters:

  • text (str | _Batch | ArrowStrings) –

    A str, or a batch as for sent_tokenize.

  • language (str, default: 'english' ) –

    The punkt_tab model name.

  • preserve_line (bool, default: False ) –

    Do not split sentences first (then no model is needed).

  • threads (int | None, default: None ) –

    For a batch, as for sent_tokenize.

Returns:

  • list[str] | list[list[str]] | list[list[str] | None] –

    The tokens; for a batch, one list per document.

Raises:

  • LookupError –

    The model is not installed (nltk.download('punkt_tab')).

  • InputError –

    text is not text.

punkt_model_available

punkt_model_available(language: str = 'english') -> bool

Whether the Punkt model sent_tokenize uses for language is installed.

The model is loaded as sent_tokenize loads it, and kept for it.

Raises:

PunktTrainer

PunktTrainer(*args: Any, **kwargs: Any) -> Any

NLTK's PunktTrainer (training is not ported: a pyroid.FallbackWarning).

Its get_params() result can be given to PunktSentenceTokenizer.

load_punkt_params

load_punkt_params(lang_dir: Any) -> PunktParameters

Read the parameters of a punkt_tab model directory.

A path is read by pyroid; an NLTK path pointer (from nltk.data.find) by NLTK, with a pyroid.FallbackWarning.

format_debug_decision

format_debug_decision(d: dict[str, Any]) -> str

Format one PunktSentenceTokenizer.debug_decisions dict as NLTK does.

align_tokens

align_tokens(
    tokens: Sequence[str], sentence: str
) -> list[tuple[int, int]]

The (start, end) offsets of tokens, found one after another in sentence.

Raises:

  • ValueError –

    A token is not in sentence after the previous one.

wordpunct_tokenize

wordpunct_tokenize(
    text: str, *, threads: int | None = None
) -> list[str]
wordpunct_tokenize(
    text: _Batch, *, threads: int | None = None
) -> list[list[str]]
wordpunct_tokenize(
    text: ArrowStrings, *, threads: int | None = None
) -> list[list[str] | None]

WordPunctTokenizer.tokenize.

blankline_tokenize

blankline_tokenize(
    text: str, *, threads: int | None = None
) -> list[str]
blankline_tokenize(
    text: _Batch, *, threads: int | None = None
) -> list[list[str]]
blankline_tokenize(
    text: ArrowStrings, *, threads: int | None = None
) -> list[list[str] | None]

BlanklineTokenizer.tokenize.

regexp_tokenize

regexp_tokenize(
    text: Any,
    pattern: Any,
    gaps: bool = False,
    discard_empty: bool = True,
    flags: int = ...,
) -> Any

RegexpTokenizer.tokenize with a tokenizer made from the arguments.