Skip to content

Unit 3 · Text Processing

3 h contact · 6 h self study Prerequisites: Unit 1 CLO 1 · CLO 2

1. Setting the scene

Scenario: Why doesn't 'bike lanes' find anything?

CityDocs' first index is built by splitting text on spaces. A case worker searches bike lanes and gets almost nothing. Investigating, the team finds:

  • the relevant council minute says "Bike lane" (singular, capital B);
  • German documents say "Radverkehrsinfrastruktur", one word;
  • a scanned letter reads "bicycIe" (OCR mistook l for I);
  • a PDF contains the date "19/1/2017", split into three meaningless tokens.

The index is not wrong: the text processing is.

Guiding questions

  1. What exactly is a "word"? Is Hewlett-Packard one or two?
  2. Should lane and lanes be the same index term? What about Windows and window?
  3. Which choices increase recall, and which damage precision?

2. Intended learning outcomes

# Outcome Bloom CLO
ILO 3.1 Describe the offline and online paths of an IR system and the role of text processing in both. UNDERSTAND 1
ILO 3.2 Distinguish word, token, term and type, and unstructured, weakly structured and fully structured representations. UNDERSTAND 1
ILO 3.3 Apply tokenisation, case folding, stemming/lemmatisation and stopword removal to a text. APPLY 2
ILO 3.4 Justify preprocessing choices by their effect on recall, precision and index size. EVALUATE 2

3. Where we are: the IR system pipeline

flowchart TB
    DC["Document collection<br/>billions of pages"] -->|"offline"| TP1["Text processing"] --> IX[("Index<br/>inverted index · embeddings")]
    Q["User query<br/>'bert vs gpt'"] -->|"online"| TP2["Query processing<br/>same steps!"]
    IX --> MR["Matching and ranking<br/>Boolean · TF·IDF · BM25 · neural"]
    TP2 --> MR
    MR --> RD["Ranked results"] --> EV["Evaluation<br/>P@10 · Recall · MAP · MRR · NDCG"]

Golden rule

The query must be processed with exactly the same steps as the documents. If documents are stemmed and lower cased but queries are not, nothing matches. A bad index cannot be fixed by a clever query.

SQL vs. IR. SQL asks "which rows satisfy this condition?" (WHERE Age > 50). IR asks "which documents are useful for this need?" (early signs of diabetes in elderly).

4. What counts as a document?

In theory simple, in practice a design decision: one PDF? one email, with or without attachments? one web page? one section of a 300 page report? The choice affects index size, ranking quality, phrase search and user satisfaction. For CityDocs, long planning reports are split into sections, so a hit points to page 212 rather than to a 300 page file.

5. Text representations

Text is a multiset of terms with counts. Word order, grammar and meaning are ignored: "dog bites man" and "man bites dog" look identical.

One evening Frodo and Sam were walking together in the cool twilight. … the time to leave Lothlórien was near.

(one,1) (evening,1) (frodo,2) (and,2) (sam,1) … (the,3) … (lothlorien,1) (near,1)

Is this a problem? In practice BoW performs remarkably well: topic words reveal content, it is fast and scalable, it fits inverted indexes perfectly, and TF·IDF and BM25 build on it.

Keep only the most informative units, found with a part of speech tagger or a Named Entity Recogniser (NER):

  • Bag of nouns: (evening,1) (Frodo,2) (Sam,1) (twilight,1) (shadow,1) (parting,1) (time,1) (Lothlórien,1)
  • Bag of named entities: (Frodo,2) (Sam,1) (Lothlórien,1)

Better focus, at the cost of an extra (and sometimes wrong) processing step.

Extract events and relations: Frodo walks with Sam; Frodo leaves Lothlórien. This requires advanced, slow and error prone NLP and is almost never used for large scale retrieval.

Rule of thumb

Real search engines use bag of words, sometimes enriched with nouns or entities. Full structure is reserved for specialised extraction tasks.

6. The standard processing pipeline

flowchart TB
    subgraph R1["Prepare"]
      direction LR
      A["1 · Extract plain text<br/>HTML · PDF · Word · OCR · email"] --> B["2 · Detect language<br/>(if multilingual)"] --> C["3 · Tokenise"]
    end
    subgraph R2["Normalise"]
      direction LR
      D["4 · Normalise<br/>case · spelling · morphology"] --> E["5 · Remove stopwords"] --> F["Clean terms<br/>ready for indexing"]
    end
    R1 --> R2

Word, token, term, type

Concept Meaning Example
Word What appears in the original text running, Houses, 123-ABC
Token One occurrence of a word in a document the 5th token of document 42
Term Normalised form stored in the index run, house, 123abc
Type A unique token class all occurrences of house

7. Tokenisation

Two approaches exist: rule based (split on whitespace and punctuation, plus handwritten exceptions) and machine learned (trained on annotated text). Simple rules work most of the time; the remainder needs hundreds of special cases:

Input Desired token(s) Why it is tricky
Hewlett-Packard one token hyphen inside a name
Denmark's Denmark + 's possessive
O'Neill one token apostrophe is part of the name
19/1/2017 one token date
192.168.0.1 one token IP address
+49 176 832 40 332 one token phone number with spaces
San Francisco two words, one concept multiword expression

The same symbol splits words in one context and belongs to the token in another.

A tokeniser is a small state machine. The simplified version below decides, character by character, when a token ends:

stateDiagram-v2
    [*] --> Outside
    Outside --> InWord : letter or digit
    Outside --> Outside : space or punctuation
    InWord --> InWord : letter or digit
    InWord --> CheckJoin : apostrophe, hyphen or dot
    CheckJoin --> InWord : next is letter or digit (O'Neill, U.S.A.)
    CheckJoin --> Outside : otherwise, emit token
    InWord --> Outside : space or punctuation, emit token

Every arrow is a design decision: should state-of-the-art stay one token? Should 19.1.2017 split at the dots?

Across languages

Lebensversicherungsgesellschaftsangestellter (life insurance company employee) has no spaces, so whitespace tokenisation yields one giant, rarely matched term. A compound splitter produces Leben + Versicherung + Gesellschaft + Angestellter.

Compare a modern subword LLM tokenizer: Leb + ens + versicherung + sges + ellschaft + s + ang + est + ell + ter, statistically efficient, but not linguistically meaningful.

For CityDocs: Radverkehrsinfrastruktur → Rad + Verkehr + Infrastruktur makes the document findable by Radverkehr.

莎拉波娃现在居住在美国东南部的佛罗里达: "Sharapova now lives in Florida, in the south east of the USA." Chinese, Japanese and Thai require a word segmentation model.

Lesson: one tokenizer does not fit all languages.

8. Normalisation

Normalisation maps different surface forms to a common searchable form.

  • Case folding: Window → window. Usually lower case everything, but "Morgen will ich in MIT": is MIT the university or the German preposition mit?
  • Punctuation/abbreviation: U.S.A. → usa. But searching C.A.T. (Caterpillar Inc.) and getting cat the animal shows how normalisation can erase distinctions.
  • Spelling / OCR correction: informaton → information, bicycIe → bicycle.

The central trade off

Normalisation increases recall (more matches) but can reduce precision (wrong matches). There is no universally correct pipeline.

Morphological normalisation

Type What it merges Meaning / POS Examples Used in IR?
Inflectional (lemmatisation) grammatical variants preserved cars → car, ran → run, better → good Yes: safe
Derivational words sharing a root may change destroy ↔ destruction, happy ↔ happiness Usually avoided

Stemming vs. lemmatisation

Method cars running better automation How
Lemmatisation car run good automation dictionary + linguistic knowledge; always a real word
Stemming car run better automat rule based suffix stripping; output may not be a word

Stemming is more aggressive than lemmatisation but less aggressive than derivational normalisation, and it is fast, simple and available for many languages.

Porter's stemmer

The classic English stemmer applies suffix rules in several stages; if several rules match, the longest suffix wins, and rules fire only if enough of the word remains (protecting short stems).

Rule Example
-sses → -ss caresses → caress
-ational → -ate relational → relate
-tional → -tion conditional → condition
-ing → ∅ running → run
-ement → ∅ (only if stem long enough) replacement → replac(e) · cement → cement
from nltk.stem import PorterStemmer, WordNetLemmatizer
# nltk.download("wordnet") once for the lemmatizer

stem = PorterStemmer().stem
lemma = WordNetLemmatizer().lemmatize

for w in ["connected", "connecting", "automation", "automatic", "running", "cement"]:
    print(f"{w:12} stem={stem(w):10} lemma(verb)={lemma(w, pos='v')}")

When does a Porter rule fire? The measure \(m\)

Porter writes every word as a sequence of consonant groups \(C\) and vowel groups \(V\):

\[ [C]\,(VC)^{m}\,[V] \]

The exponent \(m\) (the measure) counts how many vowel consonant pairs the stem contains. Many rules carry a condition such as \((m > 1)\), which prevents short stems from being cut.

Stem Pattern \(m\)
tr, tree \(C\), \(CV\) 0
trouble, oats \(C\,VC\,V\), \(VC\) 1
troubles, private \(C\,VC\,VC\), \(C\,VC\,VC\,V\) 2

Worked example: rule \((m > 1)\) ement → ∅

replacement: removing ement leaves replac \(= C\,VC\,VC\), so \(m = 2 > 1\) and the rule fires: replac. cement: removing ement leaves c \(= C\), so \(m = 0\) and the rule does not fire: cement stays.

9. Stopwords

Stopwords are very frequent, grammatically important but semantically weak words: the, is, and, of, in (German: der, die, das, und).

Why remove them When removal hurts
smaller vocabulary and postings lists phrase search: "to be or not to be"
faster retrieval, less memory titles and names: The Who, Take That
fewer false matches on weak terms queries where small words matter: flights to London vs. flights from London

Query data science in Berlin → important terms: data, science, Berlin. Stopword lists are language dependent (see e.g. ranks.nl/stopwords). Modern engines often keep stopwords in the index and downweight them via IDF instead (Unit 7).

How much text are stopwords? In the Reuters RCV1 collection, removing the 150 most frequent words deletes almost half of all token positions:

pie showData
    title RCV1 positional postings after case folding (millions)
    "150 most frequent words" : 84.6
    "All other words" : 94.5

That is why stopword removal shrinks the postings so much but the dictionary hardly at all (Unit 6).

10. Normalisation vs. query expansion

Normalisation Expansion
Idea Change indexed terms to a standard form Keep terms; expand the query with variants
Example index windows as window window → search window OR windows
Precision control Lower: merges everything Higher: Windows (capitalised) can map to the OS only
Cost Small index, fast More terms to index and search

Highly inflected languages make expansion expensive: Finnish omena (apple) has forms like omenan, omenaa, omenaan, omenat, omenien, omenoiden, omenojen, …. This is why large systems prefer normalisation, with controlled expansion where it pays off.

11. Worked example: end to end

import re
from nltk.stem import PorterStemmer

STOP = {"the", "is", "a", "an", "and", "of", "in", "to", "on", "for", "was", "were"}
stem = PorterStemmer().stem
TOKEN = re.compile(r"\d{1,2}/\d{1,2}/\d{4}|\d+(?:\.\d+){3}|\w+(?:[-']\w+)*")

def preprocess(text: str) -> list[str]:
    tokens = TOKEN.findall(text)                    # 3. tokenise (keeps dates, IPs, hyphenated words)
    tokens = [t.lower() for t in tokens]            # 4a. case folding
    tokens = [t for t in tokens if t not in STOP]   # 5. stopwords
    return [stem(t) for t in tokens]                # 4b. stemming

print(preprocess("The Bike lanes on Warschauer Str. were approved on 19/1/2017."))
# ['bike', 'lane', 'warschauer', 'str', 'approv', '19/1/2017']

Two observations: the tokenizer kept the date 19/1/2017 as one token, and the stem approv is not an English word, which is fine, because it only has to match, not to be read. Always evaluate a pipeline on real queries.

12. Classwork

Design a pipeline for CityDocs (25 min, pairs)

The corpus is ~70 % German, ~30 % English; users search in both languages; legal clerks need exact phrases.

For each step (tokenisation, case folding, compound splitting, stemming vs. lemmatisation, stopwords) decide yes / no / how, and give the risk you accept.

Discussion points

Language detection first, then language specific pipelines. Lower case, but keep a case preserving field for acronyms. German compound splitting is essential for recall. Prefer lemmatisation (spaCy de_core_news) for German; a light stemmer is acceptable for English. Keep stopwords in a positional index so clerks' exact phrases still work; remove or downweight them for ranking.

13. Check your understanding

How many tokens, terms and types are in 'The cat chased the cats'? (lower casing + stemming)

Tokens: 5. After normalisation: the, cat, chase, the, cat → 3 types/terms (the, cat, chase).

Why must queries be processed with the same pipeline as documents?

Matching happens on index terms. A query term Running will never match the indexed stem run unless the query is lower cased and stemmed the same way.

Give one example where stemming hurts precision.

operating, operative, operational → oper: a query about operating systems matches documents about military operations.

14. Key takeaways

  • Text processing turns messy words into clean terms; the query must follow the same path.
  • Bag of words discards order yet powers most search engines.
  • Tokenisation is language dependent: German compounds and spaceless scripts need special tools.
  • Normalisation, stemming and stopword removal trade precision for recall and efficiency, so justify every choice.

Project core requirement: "Preprocess the text: tokenisation, normalisation, stopword removal, stemming/lemmatisation." Your README must justify each step for your data (CLO 2). Keep before/after examples to show in the presentation.

Further reading

  • Manning, Raghavan & Schütze, Introduction to IR, ch. 2.
  • Porter, M. F. (1980), An algorithm for suffix stripping; Snowball: snowballstem.org.
  • Bird, Klein & Loper, Natural Language Processing with Python (NLTK book), ch. 3.