v9.1.1
Menu

Chapter 2: Text Preprocessing

Week 2

Master the essential techniques for cleaning and transforming raw text into structured input for NLP models. From tokenization and stemming to normalization and encoding, these preprocessing steps form the foundation of every NLP pipeline.

Topics
6
Demos
3
Videos
3
Min read
47

Chapter Overview

Raw text is messy. It contains inconsistent casing, special characters, HTML artifacts, contractions, and encoding issues. Before any NLP model can extract meaning from text, we need a systematic preprocessing pipeline to clean, normalize, and structure the input.

Text preprocessing is not a one-size-fits-all process. The right pipeline depends on your task: sentiment analysis benefits from keeping exclamation marks and emoticons, while topic modeling usually removes stopwords and punctuation. A search engine needs stemming for recall, but a chatbot needs lemmatization for grammatical responses.

This chapter covers the six core preprocessing techniques every NLP practitioner must master:

  • Tokenization: splitting text into meaningful units (words, subwords, characters)
  • Stemming & Lemmatization: reducing words to their base forms
  • Stopword Removal: filtering out low-information words
  • Regular Expressions: pattern-based text extraction and cleaning
  • Text Normalization: standardizing text format (casing, unicode, contractions)
  • Text Encoding: handling character sets, UTF-8, and multilingual text

Chapter Roadmap

Click any topic to jump in

Explainer videoInteractive demo
1
Tokenization

Splitting text into tokens — word, subword (BPE), and character strategies and their trade-offs.

Word TokenizationSubword Tokenization (BPE & WordPiece)Sentence TokenizationCharacter-Level Tokenization
Reducing vocabulary

Normalizing word forms and removing noise

2
Stemming & Lemmatization

Reducing words to base forms — fast heuristic stemming vs. linguistically correct lemmatization.

Porter StemmerSnowball StemmerWordNet LemmatizerStemming vs Lemmatization: When to Use Which
3
Stopword Removal

Filtering low-information words — standard lists, domain-specific words, and frequency-based detection.

Standard Stopword ListsDomain-Specific StopwordsStopword Removal Trade-offsFrequency-Based Stopword Detection
Cleaning and standardizing

Pattern-based extraction and format normalization

4
Regex for Text

Pattern matching and substitution — extracting emails, URLs, and cleaning HTML artifacts.

Character Classes and QuantifiersPattern Extraction with GroupsText Cleaning with SubstitutionCommon NLP Regex Patterns
5
Text Normalization

Case folding, unicode normalization, contraction expansion — standardizing text before modeling.

Case NormalizationUnicode NormalizationContraction ExpansionAccent and Diacritic Removal
Encoding the final text
6
Text Encoding

ASCII, UTF-8, and multilingual byte sequences — ensuring every character survives the pipeline.

ASCII and UTF-8Encoding Detection and ConversionHandling Special CharactersMultilingual Text and Encoding Best Practices

Topics

6 topics in this chapter

Before a model can count, embed, or classify anything, it must decide what the units of text are. Is "don't" one unit or two? Is "U.S." a word followed by a sentence end? What should happen to "unhappiest" if it never appeared in training, or to a Chinese sentence with no spaces at all? Every later step, from stopword lists to Transformer inputs, inherits the answer, and a bad split silently corrupts everything downstream.

The previous chapter, Introduction to NLP, introduced tokenization as one of the core NLP tasks. This chapter, Text Preprocessing, covers the steps that turn raw text into clean model input, and this topic begins with tokenization itself. It starts with word tokenization, which splits on spaces and punctuation using rules for contractions and abbreviations. Subword tokenization with BPE and WordPiece follows, the method behind modern language models. Sentence tokenization handles the ambiguous period, and character-level tokenization closes the topic by showing the cost of the smallest possible units.

Definition

Tokenization is the segmentation of a character string into a sequence of tokens drawn from a vocabulary VV. Word tokenizers use whitespace and punctuation rules; subword tokenizers such as BPE and WordPiece learn a vocabulary of frequent character sequences; character and byte tokenizers use individual symbols, trading a tiny vocabulary for longer sequences.

In this topic

  1. 1Word Tokenization
  2. 2Subword Tokenization (BPE & WordPiece)
  3. 3Sentence Tokenization
  4. 4Character-Level Tokenization
1 of 4
Word Tokenization

Word tokenization splits text into words and punctuation marks. The naive approach, Python's str.split(), breaks only on whitespace, so punctuation stays attached: "cheap!" and "cheap" become different tokens. Rule-based tokenizers do better. NLTK's word_tokenize() follows Penn Treebank conventions, splitting contractions such as "isn't" into "is" and "n't" and possessives such as "Smith's" into "Smith" and "'s", while keeping known abbreviations like "Dr." intact. spaCy uses prefix, suffix, and infix rules plus exception lists. The failure modes are new abbreviations, URLs, hashtags, hyphenated compounds, and languages without spaces between words, where whitespace rules do not apply at all.

Mathematical Intuition

Word tokenization splits on whitespace and punctuation boundaries. For a string of length LL characters, a regex-based tokenizer runs in O(L)O(L) time. The resulting vocabulary ∣V∣|V| for a corpus follows Heaps' law: ∣V∣≈k⋅Nβ|V| \approx k \cdot N^\beta where NN is total tokens, k≈30k \approx 30, and β≈0.5\beta \approx 0.5. A 1M-word corpus typically has ∣V∣≈30,000|V| \approx 30{,}000 unique words.

Example:

Tokenize the sentence: "Dr. Smith's car isn't in the U.S. yet!" using NLTK's word_tokenize, and compare the result with str.split().

2 of 4
Subword Tokenization (BPE & WordPiece)

Vsubword≪Vword,where V=vocabulary sizeV_{\text{subword}} \ll V_{\text{word}}, \quad \text{where } V = \text{vocabulary size}

Subword tokenizers keep the vocabulary small without unknown words. Byte Pair Encoding starts from single characters or bytes, counts adjacent pairs in a training corpus, and repeatedly merges the most frequent pair into a new symbol until the vocabulary reaches a target size, such as 50,257 for GPT-2. WordPiece, used by BERT with about 30,000 entries, picks merges that most increase training-data likelihood and marks word-internal pieces with ##. The formula's point is that the subword vocabulary VsubwordV_{\text{subword}} is far smaller than a full word vocabulary VwordV_{\text{word}}. Frequent words stay whole, rare words split into pieces, and the splits follow corpus statistics rather than morphemes.

Mathematical Intuition

Byte-level BPE starts with ∣V0∣=256\lvert V_0 \rvert = 256 byte tokens and performs MM merges, giving ∣V∣=256+M\lvert V \rvert = 256 + M plus any special tokens. Each merge picks the most frequent adjacent pair (a,b)(a, b) in the training corpus and replaces its occurrences with the new symbol abab, so every merge shortens the encoded corpus by the number of times that pair occurred. GPT-2 uses 50,000 merges, for 50,257 tokens including one special token; GPT-4's cl100k encoding has about 100,000. The merge list is applied in learned order at encoding time, so the same word always splits the same way.

Example:

Explain why subword tokenization handles the unseen word "unhappiest" gracefully.

3 of 4
Sentence Tokenization

Sentence tokenization splits a document into sentences, the input unit for summarization, translation, and many annotation tools. The hard part is the period, which can end a sentence or mark an abbreviation ("Dr.", "p.m."), a decimal ("3.5"), or an ellipsis. Question and exclamation marks inside quotations add more ambiguity. NLTK's sent_tokenize() uses Punkt, an unsupervised algorithm by Kiss and Strunk that learns abbreviations, collocations, and likely sentence starters from raw text without labels. Rules fail when an abbreviation really does end a sentence, as in "He arrived at 5 p.m." followed by a new sentence, and on informal text with missing capitals or punctuation.

Mathematical Intuition

The Punkt sentence tokenizer models abbreviation detection as a classification problem. It estimates P(abbrev∣w)P(\text{abbrev} \mid w) using features like word length, final period, and capitalization of the next word. The decision boundary is: if log⁡likelihood-ratio>θ\log \text{likelihood-ratio} > \theta, classify as abbreviation (not sentence boundary). This handles 'Dr.', 'U.S.', and 'etc.' without a hand-curated list.

Example:

Split into sentences: "Dr. Smith arrived at 3 p.m. He said, 'Hello!' Ms. Jones replied."

4 of 4
Character-Level Tokenization

Sequence length ratio=LcharLword≈5–6×\text{Sequence length ratio} = \frac{L_{\text{char}}}{L_{\text{word}}} \approx 5\text{--}6\times

Character-level tokenization makes every character a token, and byte-level tokenization makes every UTF-8 byte a token. The vocabulary is tiny, at most 256 for bytes, and nothing is ever unknown, so typos and rare names are handled naturally. The cost is length: as the formula notes, English text is roughly five to six times longer in characters than in words. Self-attention compares every pair of positions, so its cost grows with the square of the sequence length, and a fivefold longer sequence costs about 25 times more. Byte fallback inside subword tokenizers keeps the robustness without most of the cost.

Mathematical Intuition

Character-level tokenization has vocabulary ∣V∣≤256|V| \leq 256 (byte-level) but sequence length Lchar≈5LwordL_{\text{char}} \approx 5 L_{\text{word}}. For transformers with O(n2)O(n^2) attention, this means ∼25×\sim 25\times the compute cost. A 512-word document becomes ∼2,560\sim 2{,}560 characters — attention needs 25602≈6.5M2560^2 \approx 6.5M operations vs 5122≈262K512^2 \approx 262K for word-level, a 25×25\times increase.

Example:

Compare token counts for "Machine Learning" at word vs character level. What is the cost implication for a transformer?

Theory Exercise

Problem:

A search engine processes queries in 47 languages. You must choose a tokenization strategy. Word-level tokenization fails for Chinese (no spaces) and agglutinative languages like Turkish (one word = one sentence). Compare word, subword (BPE), and character tokenization for this use case. Which do you recommend and why?

Hints:
  • Consider languages without whitespace word boundaries

Coding Exercise

Problem:

Write a Python function that tokenizes text using three methods (whitespace, NLTK word_tokenize, and character-level) and compares the token counts.

Hints:
  • Use str.split() for whitespace tokenization