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") raiseUnicodeEncodeError, as everywhere in pyroid. - No pattern runs under NLTK's 5-second
regextimeout, so nothing raisesTimeoutErroron very long inputs. - Results follow
regex2026.9.29's Unicode tables; with anotherregexrelease installed, NLTK can differ on characters whose properties changed between the two. - Looking up an unseen word in
PunktParameters.ortho_contextdoes not add a 0 entry to it (NLTK'sdefaultdictgrows with every new word it tokenizes). - An NLTK
PunktParametersgiven to a tokenizer is copied (into a pyroidPunktParameters, whichtok._paramsreturns); edit it throughtok._params, since later edits of the NLTK object are not seen. - NLTK compiles a
PunktLanguageVarsobject's patterns at first use, so it keeps using the oldsent_end_charsin part of the algorithm after they are changed; pyroid uses the new ones throughout.
NLTK_VERSION
module-attribute
¶
The NLTK release whose tokenizers this module reproduces ("3.10.4").
REGEX_VERSION
module-attribute
¶
The regex release whose Unicode tables the patterns follow ("2026.9.29").
UNICODE_VERSION
module-attribute
¶
This CPython's unicodedata.unidata_version, which str case tests follow.
REASON_ABBR_WITH_ORTHOGRAPHIC_HEURISTIC
module-attribute
¶
REASON_INITIAL_WITH_ORTHOGRAPHIC_HEURISTIC
module-attribute
¶
REASON_NUMBER_WITH_ORTHOGRAPHIC_HEURISTIC
module-attribute
¶
REASON_INITIAL_WITH_SPECIAL_ORTHOGRAPHIC_HEURISTIC
module-attribute
¶
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
¶
Lowercase abbreviations, without their final period ("dr").
collocations
instance-attribute
¶
Word pairs whose first word ends in a period that is not a sentence break.
ortho_context
instance-attribute
¶
ortho_context: defaultdict[str, int]
Orthographic contexts (bit flags) each word type was seen in.
clear_ortho_context ¶
clear_ortho_context() -> None
Replace ortho_context with an empty defaultdict(int).
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.
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: apyroid.FallbackWarning), or aPunktParameters(pyroid's or NLTK's) to use.Noneor 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
PunktTokenor a subclass; anything but the default runs in NLTK.
train ¶
Return parameters trained on train_text (with NLTK), or train_text if not a str.
tokenize ¶
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]
The same as tokenize.
span_tokenize ¶
span_tokenize(
text: str,
realign_boundaries: bool = True,
*,
threads: int | None = None,
) -> Iterator[tuple[int, int]]
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.
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 ¶
Whether text contains a sentence break that is not at its last token.
sentences_from_text_legacy ¶
The sentences of text, found by annotating every token (NLTK's older method).
sentences_from_tokens ¶
Group word tokens into sentences (lists of the same tokens).
debug_decisions ¶
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.
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–langis not a str. -
ValueError–langcannot name one model. -
LookupError–The model is not installed (
nltk.download('punkt_tab')).
MacIntyreContractions ¶
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.
tokenize ¶
RegexpTokenizer ¶
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
.patternis 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.
span_tokenize ¶
The (start, end) offsets of the tokens in text (a generator, as NLTK's).
WhitespaceTokenizer ¶
WhitespaceTokenizer()
BlanklineTokenizer ¶
BlanklineTokenizer()
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 ¶
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_tabmodel name ("english","german", ...). -
threads(int | None, default:None) –For a batch:
Noneuses the whole shared pool,nat mostntasks,1the calling thread.
Returns:
-
list[str] | list[list[str]] | list[list[str] | None]–The sentences; for a batch, one list per document (
Nonefor an Arrow null).
Raises:
-
LookupError–The model is not installed (
nltk.download('punkt_tab')). -
TypeError–languageis not a str. -
ValueError–languagecannot name one model. -
InputError–textis not text.
word_tokenize ¶
word_tokenize(
text: str,
language: str = "english",
preserve_line: bool = False,
*,
threads: int | None = None,
) -> list[str]
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_tabmodel 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–textis not text.
punkt_model_available ¶
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:
-
TypeError–languageis not a str. -
ValueError–languagecannot name one model.
PunktTrainer ¶
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 one PunktSentenceTokenizer.debug_decisions dict as NLTK does.
align_tokens ¶
The (start, end) offsets of tokens, found one after another in sentence.
Raises:
-
ValueError–A token is not in
sentenceafter the previous one.