Text preprocessing: tokenisation, stemming and lemmatisation
Practical and exam-focused notes on tokenisation, stemming and lemmatisation: definitions, algorithms (Porter), Python syntax, worked code examples, common mistakes and exam guidance.
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
Text preprocessing converts raw text into the canonical, compact pieces a search engine or IR system can index and match. Engineers use tokenisation, stemming and lemmatisation when building inverted indices, computing TF-IDF, running clustering or training classifiers — any place where consistent term forms and accurate token boundaries improve retrieval and reduce index size.
Key ideas
Define every term first, then build up algorithms and assumptions.
Token: a contiguous sequence of characters in text that is treated as a single unit for processing (example: the word "cats"). Use this exact word when answering definitions.
Tokenisation: the process of splitting raw text into a sequence of tokens. Assumptions: input is a Unicode string; decisions must be made for punctuation, case, numbers, contractions and languages without whitespace (e.g. Chinese, Japanese, Thai). Typical choices (each is a design decision, not a law): split on whitespace and punctuation; keep or drop punctuation tokens; treat contractions as single or multiple tokens.
Normalisation: operations applied after tokenisation to make tokens comparable. Common normalisations: lowercasing, Unicode normalization (NFC/NFKC), removing diacritics, canonicalising punctuation, and digit normalisation (e.g. mapping "1,000" → "1000"). Define: normalisation = deterministic mapping f(token) → token' so equal surface forms map to the same canonical form. For robust Unicode case handling, prefer casefolding (e.g., 'ß'→'ss'); be careful with language-specific casing (e.g., Turkish dotted/undotted I).
Stop words: frequent function words (like "the", "is") removed because they often add little retrieval value. Define: a stop list is a hand-curated or statistically chosen set S such that tokens in S are dropped during indexing or query processing.
Stemming: an algorithmic process that chops affixes from words to produce a base form (the stem), not necessarily a linguistically valid word. Define precisely: stemming = a rule-based or statistical mapping s(word) → stem where stems are not required to be dictionary lemmas. Common assumption: aggressive conflation is acceptable if it improves recall even at some precision cost.
Lemmatisation: a linguistically informed process that maps an inflected word to its lemma, the dictionary head-form (e.g. "ran" → "run"), typically using morphological analysis and part-of-speech (POS) information. Define: lemmatisation = morphological analysis + dictionary lookup + optional POS disambiguation; output must be a valid lemma in the target lexicon.
Morphology terms: affix (prefix/suffix), inflection (changes for tense/number/gender), derivation (creates a new word class). Distinguish: stemming often removes derivational affixes too (e.g. "national"→"nation"), while lemmatisation usually only reverses inflection.
Porter Stemmer core definitions (universities expect these exact formal parts):
- Treat characters as vowels or consonants where vowel = {a,e,i,o,u} and
yis treated as a vowel if and only if it is preceded by a consonant; otherwiseyis a consonant (Porter defines a consonant function c(i) with this rule). - Define a word's structure as sequences of consonant (C) and vowel (V) groups. For a word, define the measure
mas the number of VC sequences: if the word can be written as (C)(VC)^m(V), then m is that count. Example: for "trouble" the C/V grouping is C V C V (tr|ou|bl|e), so m = 2. - Porter rules apply conditionally: suffix replacement rules apply only if the remaining stem has m > 0 (or other tests). Steps: Step 1a/b/c (plural and past participle), Step 2 (map double suffixes), Step 3 (further suffixes), Step 4 (remove certain suffixes), Step 5 (trim final 'e' and double consonant).
- State exact conditional test form: a rule is expressed as
if word ends with 'XXX' and condition holds then replace suffix 'XXX' with 'YYY'where condition can bem>0,m>1, or*v*(contains a vowel), or*d(ends with double consonant), or*o(ends with consonant-vowel-consonant with final not w/x/y).
- Treat characters as vowels or consonants where vowel = {a,e,i,o,u} and
Lemmatisation algorithm (high level):
- POS tag the token (noun/verb/adjective/adverb).
- For the token and its POS, consult morphological rules (regular inflection reversal). If irregular or ambiguous, consult lemma dictionary (WordNet-style) keyed by POS.
- Return lemma if found; otherwise, fall back to token lowercased or to a stem.
Tokenisation challenges and choices (explain how to draw a small diagram):
- Draw three columns labelled "Input", "Rule applied", "Output tokens". Add rows for examples: "don't" → split as [don, 't] or [do, n't] or [don't]; "e-mail" → [e-mail] or [e, -, mail] or [email]. For languages without spaces, draw a Chinese/Japanese/Thai string and show segmentation options.
Note where choices affect downstream systems: token boundaries affect inverted index terms, stemming affects vocabulary size and term conflation, lemmatisation improves precision for irregular forms (important for language modelling and for query expansion in ontology-aware IR).
Formulas
For this programming/topic, give the syntax and short explanation (one per line):
text.split() — Python string split on whitespace; returns list of substrings. Use when simple whitespace tokenisation suffices.
re.findall(r"\w+", text) — Python regex to find word characters (letters, digits, underscore) under Unicode; returns list of tokens. Useful for simple patterns; excludes hyphens/apostrophes by default—adjust the pattern if needed.
nltk.word_tokenize(text) — NLTK tokenizer (Punkt) that handles punctuation and common contractions; requires nltk.download('punkt').
PorterStemmer().stem(token) — NLTK Porter stemmer call; returns a stem string. Apply to each token (usually after lowercasing).
WordNetLemmatizer().lemmatize(token, pos='n') — NLTK WordNet lemmatiser; second argument is WordNet POS ('n', 'v', 'a', 'r'). Better results if POS mapped from nltk.pos_tag.
m = count_VC_sequences(stem) — abstract formula: m is the count of vowel-consonant groups in the stem; used in Porter rules. Implement by scanning characters for transitions V→C.
SI units are not applicable for string-processing topics.
Worked examples
Example 1 — tokenisation and normalisation (theory, step-by-step): Input: "Dr. Rao's e-mail: Rao_2020@example.com — well-known scientist." Steps:
- Lowercase: "dr. rao's e-mail: rao_2020@example.com — well-known scientist."
- Decide policy: keep email as single token, split on whitespace, preserve punctuation inside tokens, including periods in abbreviations and the underscore in email/usernames.
- Apply tokeniser that treats email regex as a single match, abbreviations as single tokens, and splits on other punctuation. Output tokens (one possible correct set): ["dr.", "rao's", "e-mail", "rao_2020@example.com", "well-known", "scientist", "."] Explain: alternative choices (strip punctuation, split hyphen) are acceptable if stated — always state the rule in an answer.
Example 2 — Python program: tokenisation, Porter stemming, lemmatisation using NLTK (complete program). This will run given NLTK resources are downloaded.
# Requires: pip install nltk
import nltk
from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer
from nltk.stem import WordNetLemmatizer
from nltk.corpus import wordnet
# download required resources (run once)
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('wordnet')
nltk.download('omw-1.4')
text = "Cats chased mice. Running, runs, and ran are forms of run."
# Tokenisation
tokens = word_tokenize(text)
print('TOKENS =', tokens)
# Stemming (Porter)
ps = PorterStemmer()
stems = [ps.stem(t.lower()) for t in tokens if t.isalpha()]
print('STEMS =', stems)
# Lemmatization (WordNet) with POS mapping
wnl = WordNetLemmatizer()
# POS tag then map to WordNet POS
pos_tags = nltk.pos_tag(tokens)
map_pos = lambda tag: 'v' if tag.startswith('V') else ('n' if tag.startswith('N') else ('a' if tag.startswith('J') else 'n'))
lemmas = [wnl.lemmatize(t.lower(), pos=map_pos(tag)) for (t, tag) in pos_tags if t.isalpha()]
print('LEMMA =', lemmas)
Sample exact output (assuming standard NLTK behaviour): TOKENS = ['Cats', 'chased', 'mice', '.', 'Running', ',', 'runs', ',', 'and', 'ran', 'are', 'forms', 'of', 'run', '.'] STEMS = ['cat', 'chase', 'mice', 'run', 'run', 'and', 'ran', 'are', 'form', 'of', 'run'] LEMMA = ['cat', 'chase', 'mouse', 'run', 'run', 'and', 'run', 'be', 'form', 'of', 'run']
Note: I list this output to show the typical mapping of irregular forms: Porter does not map "mice"→"mouse" or "ran"→"run", while WordNet lemmatisation maps "mice"→"mouse" and "ran"→"run" when POS-tagged. Please verify against your NLTK version.
Example 3 — model answer (theory long question) — "Compare stemming and lemmatisation and explain when to use each in an IR system": A full-marks answer states definitions (above), lists algorithmic differences (rule-based suffix chopping vs morphological analysis + dictionary), shows effects on recall and precision (stemming increases recall, sometimes reduces precision; lemmatisation is conservative and improves precision for irregulars), mentions runtime and resource tradeoffs (lemmatisation needs POS tagger and lexicon — higher CPU and memory), and gives examples ("running"→stem:"run"; "ran"→stem:"ran" but lemma:"run"), then concludes with when to choose each (use stemming for large-scale retrieval where speed and index size matter; use lemmatisation for precise NLP tasks like question answering or when morphological accuracy matters). Cite effect on inverted index vocabulary size and link to later topics like TF-IDF and inverted index.
Common mistakes
- Ignoring case-normalisation and then claiming different token counts (always mention lowercasing decision).
- Claiming that stemming always improves recall with no precision trade-off — must say "typically" and explain counterexamples (over-stemming conflates unrelated roots; under-stemming fails to conflate morphological variants, e.g., analysis/analyses).
- Confusing the Porter algorithm details: forgetting to define
m, or mis-stating the*ocondition. - Forgetting to POS-tag before lemmatisation in examples where it matters (e.g. "better" as adjective vs adverb).
For your exam
Question types you will see: short definitions (define tokenisation, stemming, lemma), short notes (differences), derivations/explanations (explain Porter measure m and work one rule), programs (tokenise and stem using Python), diagrams (tokenisation choices table), and comparative essays (when to use stem vs lemma). A full-marks answer should:
- Give precise definitions (bold terms where required),
- State assumptions and design choices,
- Show algorithmic steps or pseudo-code for Porter or lemmatisation flow,
- Give a small worked example illustrating the rule or result,
- Mention effects on downstream IR components (inverted index, TF-IDF, vector space model).
Quick check
- Define tokenisation in one sentence.
- What is the Porter measure
m? (short answer) - Why prefer lemmatisation to stemming for "ran" → "run"?
Answers: 1. Tokenisation is splitting raw text into discrete tokens (units) for processing. 2.
mis the number of vowel-consonant (VC) sequences in the stem; if word = (C)(VC)^m(V) then thatmis used as condition in Porter rules. 3. Because lemmatisation uses morphological/dictionary knowledge and POS to map irregular forms (like "ran") to their dictionary lemma "run", while simple stemmers may not handle irregulars.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?