liveBook · Manning

Regular expression tokenizer

As explained in Natural Language Processing in Action, Second Edition

A regular expression tokenizer is a tokenizer that divides text into tokens by applying regular-expression rules.

A regular expression tokenizer divides text into tokens by applying pattern rules. It favors speed over the linguistic accuracy and additional tags provided by fuller NLP pipelines. section 2.1.5

A compact Python tokenizer

The pattern r'\w+(?:\'\w+)?|[^\w\s]' keeps word-internal apostrophes while separating punctuation: re.findall(pattern, text) produced about 20,000 tokens and ran in 8.77 milliseconds on the demonstrated text. section 2.1.5

Use the technique when:

  • Processing large collections where tokenizer throughput matters more than linguistic annotation. section 2.1.5
  • Replacing a slow full spaCy pipeline when embeddings, tagging, parsing, lemmatization, or named entities are unnecessary. section 2.1.5
  • Accepting reduced accuracy in exchange for substantial processing-time reductions, including medical-record parsing at scale. section 11.2.2
>>> pattern = r'\w+(?:\'\w+)?|[^\w\s]'
>>> tokens = re.findall(pattern, text)    #1
>>> f'{round(len(tokens) / 10_000)}0k'
'20k'
>>> %timeit re.findall(pattern, text)
8.77 ms ± 29.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Inspect the runnable regular-expression tokenization benchmark and its resulting token count. section 2.1.5

>>> re.split(r'[!.?]+[\s$]+',
...     "Hello World.... Are you there?!?! I'm going to Mars!")
['Hello World', 'Are you there', "I'm going to Mars!"]

Inspect a related regular-expression sentence split and see how punctuation rules affect boundaries. section 11.2.2

How Natural Language Processing in Action, Second Edition covers it

How deep it goes
Shows executable patterns, benchmarks, and trade-offs, but stops short of sophisticated linguistic disambiguation.
Examples
Uses Python re.findall patterns, punctuation splits, spaCy timing comparisons, and medical-record processing.
What it assumes
Assumes basic Python and regular-expression familiarity while demonstrating the tokenizer pattern directly.
What you can do after
Build it with Python regular expressions and evaluate its throughput against spaCy or NLTK tokenizers.
How it connects
Connects tokenization with sentence segmentation, natural language processing, and spaCy pipeline configuration.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Natural Language Processing in Action, Second Edition. The section links point to the parts of the book it draws on.