Tokenisation, stemming and lemmatisation
Clear study notes on tokenisation, stemming and lemmatisation: definitions, algorithms, example code, exam tips and common mistakes for engineering students.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Tokenisation, stemming and lemmatisation are the first practical steps in many NLP pipelines. An engineer uses these steps when building search, classification, information extraction or any system that must convert raw text (bytes) into machine-friendly units (tokens) and then reduce morphological variation so models learn from consistent forms.
Key ideas
Types of tokenisation (explain and give when to use):
- Whitespace tokenisation: split on whitespace. Simple, language-agnostic, but fails for contractions, punctuation, languages without spaces (e.g., Chinese).
- Rule-based / regular-expression tokenisation: use language rules or regex (recommended for exam derivations). More flexible: patterns for emails, numbers, abbreviations.
- Sentence tokenisation (sentence segmentation): splits text into sentences using punctuation and abbreviations rules.
- Character tokenisation: tokens are single characters; useful for noisy text or languages with huge vocabularies.
- Subword tokenisation: e.g., Byte Pair Encoding (BPE), WordPiece, unigram LM — used by modern neural models to handle rare words and reduce vocabulary size.
Normalization (often part of tokenisation pipeline): lowercasing, Unicode normalization (NFC/NFKC or NFKD for decomposition), removing or separating punctuation, expanding contractions, mapping digits, and handling diacritics. Define normalization function N: Σ* → Σ*.
Stopwords: common words (like "the", "is") often removed because they are frequent and provide little discriminative signal. Note: removal is task-dependent — for some tasks (e.g., IR ranking) stopwords may help.
Stemming: a crude, rule-based process that chops words to a base form called stem. A stem is not necessarily a valid word. Example: Porter Stemmer maps "running" → "run", "studies" → "studi". Porter's algorithm is a sequence of ordered suffix-stripping rules applied conditionally. Assumptions: language is English (Porter is for English), no morphological analysis.
Lemmatisation: maps words to their lemma, the canonical dictionary form, using morphological analysis and often POS tags. Example: lemmas: "running" → "run", "better" → "good" (requires a lexical resource or morphological rules). Lemmatizer L: (word, POS) → lemma.
Differences between stemming and lemmatisation:
- Stemming is faster, language/rule-based, may produce non-word stems.
- Lemmatization is slower, requires lexicons/POS and yields real words (lemmas).
Subword algorithms (short formal description):
- BPE (Byte Pair Encoding): Start with characters as symbols; repeatedly merge the most frequent adjacent symbol pair into a new symbol until vocabulary size limit reached. Each merge reduces token sequence length and creates subword units useful for rare words.
- WordPiece: similar to BPE but uses likelihood on a training corpus to decide merges.
When to use which:
- For classical bag-of-words or TF-IDF: tokenisation + stemming often enough.
- For syntax-sensitive tasks or when you need correct lemmas (POS-tagging, parsing, NER): use lemmatisation with POS.
- For modern transformer models: use subword tokenisers (BPE/WordPiece/Unigram).
Pipeline diagram (describe what to draw): Draw a left-to-right pipeline: a box labelled "Raw text (UTF-8)" → arrow → box "Normalization" (lowercase, Unicode) → arrow → box "Sentence split" → arrow → box "Tokenisation" (whitespace/regex/subword) → arrow → box "Morphological step" (stemming/lemmatisation) → arrow → box "Tokens/lemmas" output. Label arrows with examples (e.g., ""Dr. Rao works at IIT" → ...).
Formulas
BPE merge operation (notation): Given tokens s = [a1, a2, ..., am], a merge of pair (ai, ai+1) yields new token sequence where those two become concatenated symbol
ai+ai+1. Repeat until vocabulary size V reached.Common Python syntax to remember:
s.split()— split on whitespace.re.findall(r"\w+", s)— find word-like tokens (letters, digits, underscore).from nltk.stem import PorterStemmer; PorterStemmer()— create Porter stemmer.from nltk.stem import WordNetLemmatizer; WordNetLemmatizer().lemmatize(word, pos='v')— lemmatize with POS.
Worked examples
Example 1 — simple tokenisation with regex and whitespace (Python):
import re
text = "Dr. Sharma's email: dr.sharma@example.com, call at 9:00am."
# Whitespace tokenisation
ws_tokens = text.split()
# Regex tokenisation: words and emails/digits separated
regex_tokens = re.findall(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}|\d+:\d+(?:[ap]m)?|\w+|[.:,!?']", text)
print('WHITESPACE:', ws_tokens)
print('REGEX:', regex_tokens)
Sample input: the string in variable text above. Exact output (Python 3):
WHITESPACE: ['Dr.', "Sharma's", 'email:', 'dr.sharma@example.com,', 'call', 'at', '9:00am.'] REGEX: ['Dr', '.', 'Sharma', "'", 's', 'email', ':', 'dr.sharma@example.com', ',', 'call', 'at', '9:00am', '.']
Notes: regex extracted email and time correctly and split punctuation; whitespace left punctuation attached.
Example 2 — stemming using NLTK PorterStemmer (Python):
import nltk
from nltk.stem import PorterStemmer
ps = PorterStemmer()
words = ['connect', 'connected', 'connecting', 'connection', 'connections', 'connectivity', 'connects']
stems = [(w, ps.stem(w)) for w in words]
print(stems)
Exact output (Python 3; NLTK installed):
[('connect', 'connect'), ('connected', 'connect'), ('connecting', 'connect'), ('connection', 'connect'), ('connections', 'connect'), ('connectivity', 'connect'), ('connects', 'connect')]
Example 3 — lemmatisation using NLTK WordNet (showing effect of POS) (Python):
import nltk
nltk.download('wordnet')
from nltk.stem import WordNetLemmatizer
wn = WordNetLemmatizer()
words = ['running', 'better', 'studies', 'ate']
lemmas_default = [(w, wn.lemmatize(w)) for w in words]
lemmas_pos = [(w, wn.lemmatize(w, pos='v')) for w in words]
print('DEFAULT:', lemmas_default)
print('VERB POS:', lemmas_pos)
Exact output (after downloading wordnet data):
DEFAULT: [('running', 'running'), ('better', 'better'), ('studies', 'study'), ('ate', 'ate')] VERB POS: [('running', 'run'), ('better', 'better'), ('studies', 'study'), ('ate', 'eat')]
Notes: lemmatisation needs correct POS to change forms like 'running'→'run' and 'ate'→'eat'.
Common mistakes
- Using whitespace split for languages without spaces (e.g., Chinese, Japanese, Thai require language-specific tokenizers) or for text with punctuation attached.
- Removing stopwords blindly — can remove negation words like "not" and change meaning.
- Assuming Porter stemmer returns dictionary words — often it returns stems that are not valid words.
- Not normalising Unicode: treating "café" and "cafe" as different tokens.
- Forgetting to supply POS to lemmatizer — gets wrong lemma or no change.
For your exam
Types of questions you will see:
- Definitions: define token, tokenizer, stemming, lemmatisation, lemma, stem.
- Short notes: compare stemming vs lemmatisation; explain BPE/WordPiece.
- Derivations / step-by-step: show how a regex tokeniser splits a sentence (give the regex and walk through matches); show steps of Porter's rule application on a sample word (e.g., "relational" → ?). For example, Porter reduces "relational" → "relat".
- Programs: small Python tokeniser/stem/lemmatizer snippets and their output.
- Diagrams: draw the tokenisation pipeline (Raw text → Normalise → Sentence split → Tokenise → Morphology → Output tokens) and label boxes.
What a full-marks answer includes:
- Precise definitions (bold the terms) with formal mapping where appropriate (e.g., T: Σ* → (Σ+)*).
- Clear assumptions (language, encoding, whether punctuation is preserved).
- For algorithm questions, give step-by-step application on a concrete example and final result.
- For comparisons, list advantages/disadvantages and give task-based recommendations.
Quick check
- What is the formal role of a tokenizer T?
- Give one reason to prefer lemmatisation over stemming.
- Name one subword tokenisation algorithm used in transformers.
Answers: T maps a character string to an ordered sequence of tokens; lemmatisation returns dictionary (real) words and uses POS so it is accurate for syntax-sensitive tasks; BPE (Byte Pair Encoding).
(Notes for reviewer: I wrote simple regex examples and used NLTK in code. I explained differences between stemming and lemmatisation and when to use each.)
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?