Contents Language as Data Code Course home

Chapter 2Corpora and Preprocessing

After this chapter you will be able to

  • distinguish stemming from lemmatisation and say when each is the right choice;

  • choose a preprocessing pipeline for a task, and say what each dropped step would have cost;

  • compute the minimum edit distance between two strings and trace the alignment that produces it;

  • count the tokens and types of a text, and explain why a count means nothing without the tokeniser that made it.

The corpus is the raw material

Every method in this book starts from the same ingredient, a large body of text. That holds as much for counting word pairs as for training a neural network. A corpus (plural corpora) is a collection of text gathered for study or training, and every empirical claim in the field is tested against one.

Two facts make the corpus central. The distributional hypothesis of Chapter 6 says that the meaning of a word shows in how it is actually used, and every model in Part III learns its parameters by counting or predicting over text. The corpus is therefore the source of everything a system will ever know, and choosing it is the most consequential decision you will make. Train a model only on legal contracts and it will speak like a contract. Train it on the open web and it inherits the web’s knowledge and its prejudices together.

The corpora the field has used tell its history. The Brown Corpus of 1961 held a carefully balanced million words of American English, and the Penn Treebank annotated Wall Street Journal text with syntactic structure. Both were workhorses of the statistical era. Parallel corpora made statistical machine translation possible, the classic one being the Canadian Hansards, which pairs English and French transcripts of parliament.

Then the scale exploded. Large language models are pretrained on web-scale corpora such as Common Crawl, C4, The Pile, RefinedWeb and FineWeb, which are measured in trillions of tokens, not millions of words. That jump is one of the deepest reasons the models of Part IV can do what earlier ones could not. It is also why their failures of bias and provenance are so hard to audit, a problem the final chapters take up.

Preprocessing: decisions that shape the data

Raw text is rarely fed to a model as it stands. Between the corpus and the model sits preprocessing, a sequence of transformations that put the text into a standard form. The classical pipeline for English is a familiar list:

  • tokenisation, splitting text into tokens, the units a model reads, usually words or pieces of words

  • case folding, lowercasing everything

  • stemming, crudely stripping suffixes, so running becomes run

  • lemmatisation, mapping a word to its dictionary root, so best becomes good

  • stripping punctuation and normalising whitespace

  • expanding contractions, so isn’t becomes is not

  • removing stop words, the very frequent low-content words such as the and of

Each item looks harmless on its own. The rest of this section shows that every one of them changes what a model can learn, and it begins with the two steps that are most often confused.

Stemming against lemmatisation

A stemmer chops. It applies suffix rules without consulting a dictionary, so it is fast and language-specific, and it is indifferent to whether the result is a word. The Porter stemmer is the classic example. A lemmatiser looks up instead. It maps a word to its dictionary headword, its lemma, using a vocabulary and usually the part of speech as well. It is slower and needs the dictionary, but its output is always a dictionary word. The table shows what each does to the same eight inputs.

word Porter stemmer lemmatiser agree?
running run run yes
universities univers university no
better better good no
was wa be no
studies studi study no
caring care care yes
organization organ organization no
mice mice mouse no

The two agree on only two of the eight words, and the disagreements fall into three groups. The stemmer produces non-words: univers, wa and studi are not English. That costs nothing if the output is only ever an index key, and it is unacceptable if a human will read it. The stemmer also cannot handle irregular forms, so it leaves better and mice untouched for want of a suffix to strip, and only a dictionary knows that better is a form of good or that mice is the plural of mouse. Most damaging, the stemmer merges words that should stay apart. Organization becomes organ, so a document about corporate structure now shares a term with a document about the human body, and university becomes univers, which swallows universal and universe along with it.

Which one you want depends on the job. A search engine usually prefers the stemmer, because finding every relevant document matters more than avoiding irrelevant ones, the output is never shown to anyone, and speed counts. A grammar checker or a machine translation system needs the lemmatiser, since it must know that was is a form of be before it can reason about tense.

Every step costs you something

The comparison generalises. No preprocessing step is automatically correct, because each one destroys information along with the noise. Case folding is the standard example: lowercasing collapses US the country into us the pronoun, and Apple the company into apple the fruit. A small convenience has been bought with a genuine distinction.

Removing stop words carries a subtler cost, because it discards exactly the function words that carry the syntax. Strip them from “the cat sat on the mat” and you get “cat sat mat”, which still says roughly what the sentence was about. Now strip them from “the man bit the dog” and from “the dog bit the man”. Both collapse to “man bit dog”. The two sentences said opposite things, and preprocessing has made them identical.

The governing principle is that preprocessing is task dependent. A topic classifier benefits from collapsing variants and dropping function words, while a system that must respect case, punctuation or grammar is ruined by the same steps. Understand the problem first and choose the pipeline second.

One historical shift reverses the classical advice. Modern language model pipelines do minimal preprocessing. They keep the case, the punctuation and the stop words, and lean on subword tokenisation, the byte pair encoding of Chapter 5, to turn raw text into units a model can consume. Aggressive cleaning made sense when models were small and every dimension was precious. A large model can simply learn that Apple and apple differ by context, so throwing that distinction away at the door is a loss. For this reason the field has moved steadily towards doing less to the text and letting the model do more, as Figure 2.1 shows.

Figure 2.1. Two preprocessing philosophies. The classical pipeline removes information before the model sees the text. The modern pipeline keeps the text almost intact and lets the model learn which distinctions matter.

Measuring string distance

Preprocessing treats a word as a unit and decides what to do with it. Two further jobs need a different kind of tool altogether. Correcting a misspelling and finding near duplicate documents both ask how close two strings are as sequences of characters, and the vector similarities of later chapters cannot answer that question.

The classical tool is minimum edit distance, also called Levenshtein distance. It is the smallest number of single-character insertions, deletions and substitutions that turn one string into another. A small dynamic program computes it. Let D[i,j]D[i,j] be the distance obtained by comparing the first ii characters of source ss with the first jj of target tt. Then

D[i,j]=min⁡{D[i−1,j]+del(si)(delete si)D[i,j−1]+ins(tj)(insert tj)D[i−1,j−1]+sub(si,tj)(match or substitute)(2.1)\begin{equation} D[i,j] = \min\!\begin{cases} D[i-1,j] + \mathrm{del}(s_i) & \text{(delete } s_i) \\ D[i,j-1] + \mathrm{ins}(t_j) & \text{(insert } t_j) \\ D[i-1,j-1] + \mathrm{sub}(s_i,t_j) & \text{(match or substitute)} \end{cases} \label{eq:editdist} \quad\text{(2.1)} \end{equation}

with base cases D[i,0]=iD[i,0] = i and D[0,j]=jD[0,j] = j. The answer sits in the bottom right cell, D[|s|,|t|]D[|s|,|t|]. In words, the cheapest way to align two prefixes is the cheapest of three smaller alignments plus one more edit. Fill the table left to right and top to bottom, and the whole thing costs O(|s||t|)O(|s|\,|t|) time.

The penalties

The three functions del\mathrm{del}, ins\mathrm{ins} and sub\mathrm{sub} are the penalties, or costs. They are a choice, not a law. Levenshtein distance takes the simplest choice:

del(a)=1,ins(b)=1,sub(a,b)={0if a=b(a match is free)1otherwise(2.2)\begin{equation} \mathrm{del}(a) = 1, \qquad \mathrm{ins}(b) = 1, \qquad \mathrm{sub}(a,b) = \begin{cases} 0 & \text{if } a = b \quad \text{(a match is free)}\\ 1 & \text{otherwise} \end{cases} \label{eq:editcosts} \quad\text{(2.2)} \end{equation}

A match costs nothing, so when two characters agree the diagonal move carries the alignment forward. Other choices are common, and they change the answer. Jurafsky and Martin often set sub=2\mathrm{sub} = 2, reasoning that a substitution amounts to a deletion plus an insertion, and under that setting kitten to sitting costs 55 rather than 33. Spelling correctors sometimes make sub(m,n)\mathrm{sub}(m, n) cheaper than sub(m,q)\mathrm{sub}(m, q), because mm and nn sit adjacent on the keyboard and are confusable by ear, while biological sequence alignment uses a whole substitution matrix.

A distance quoted without its penalties is not a number anyone can reproduce, so state them every time. Everything below uses Equation (2.2).

A worked example: cat to cart

Take s=𝚌𝚊𝚝s = \texttt{cat} and t=𝚌𝚊𝚛𝚝t = \texttt{cart}. The table gets one row per character of the source and one column per character of the target, each plus one for the empty string, which makes it 44 rows by 55 columns.

Step 1: the first four cells.

Start in the corner, where the base cases fill the top row and the left column, giving D[0,0]=0D[0,0]=0, D[0,1]=1D[0,1]=1 and D[1,0]=1D[1,0]=1. Those say that turning an empty string into c costs one insertion, and that turning c into an empty string costs one deletion. Now compute the first interior cell, D[1,1]D[1,1], which compares c with c. Take the smallest of three options, where deleting gives D[0,1]+1=2D[0,1]+1 = 2, inserting gives D[1,0]+1=2D[1,0]+1 = 2, and matching gives D[0,0]+0=0D[0,0]+0 = 0. The match wins.

# c
# 0 1
c 1 0
Step 2: the first pass.

Carry that row across, where each new cell asks the same three-way question about a longer prefix of the target.

# c a r t
# 0 1 2 3 4
c 1 0 1 2 3
a 2
t 3

Along the row for c, once the c itself has matched, every further column costs one more insertion, because the source has run out of letters to align, and so the row climbs 0,1,2,30, 1, 2, 3.

Step 3: the finished table.

Fill the remaining rows the same way, with cells on the cheapest path shown in bold and the answer boxed.

# c a r t
# 0 1 2 3 4
c 1 0 1 2 3
a 2 1 0 1 2
t 3 2 1 1

The boxed cell is the answer, so the edit distance from cat to cart is 𝟏\mathbf{1}.

Figure 2.2. The finished table for cat to cart, with the traced path drawn from the answer back to the origin. A diagonal move matches or substitutes, a move to the left inserts, and a move upwards deletes.
Step 4: the trace.

The number alone does not say which edits were made. For that, walk backwards from the boxed cell, each time to whichever neighbour produced it.

cell came from move operation
D[3,4]=1D[3,4] = 1 D[2,3]=1D[2,3] = 1 diagonal match t with t, cost 0
D[2,3]=1D[2,3] = 1 D[2,2]=0D[2,2] = 0 left insert r, cost 1
D[2,2]=0D[2,2] = 0 D[1,1]=0D[1,1] = 0 diagonal match a with a, cost 0
D[1,1]=0D[1,1] = 0 D[0,0]=0D[0,0] = 0 diagonal match c with c, cost 0

Read forwards, the alignment is plain: keep c, keep a, insert r, keep t. This is one insertion, so the distance is 11. Figure 2.2 draws the same path on the table. Each move carries a meaning. A diagonal step consumes one character from each string, a left step consumes one from the target only and is therefore an insertion, and an upward step consumes one from the source only and is a deletion.

Run it. The script that produced these three tables and the trace is code/worked_examples/edit_distance.py. Run it on your own pair of words, or change the penalties and watch the answer move.

Run it

The canonical larger example is kitten to sitting, whose distance is 33 under these penalties: substitute s for k, substitute i for e, then insert a final g. That table runs 77 by 88, and building it by hand is the fastest way to be sure you have the recurrence right. A spelling corrector uses exactly this machinery, returning the dictionary word at minimum edit distance from the misspelling, and corpus deduplication uses a relative of it to flag documents that differ only in boilerplate. The same dynamic programming idea returns later in the book. Generalise it from characters to words, and from distance to reward, and you have sequence alignment, which recurs throughout computational linguistics.

The edit distance table for cat and cart filled in, with the cheapest path traced
Edit distance is built from smaller problems. Each cell holds the cheapest way to turn one prefix into another, and the path back through the table recovers the edits.

Knowing your corpus

Whatever the pipeline, measure the text before you model it. A handful of simple statistics already says a great deal. The token count is the total number of word occurrences. The vocabulary size, or type count, is the number of distinct words. The type-token ratio is the vocabulary divided by the token count, which serves as a first index of lexical variety.

These are not idle tallies, because they raise two questions. How does the vocabulary grow as the text gets longer, and how steeply do word frequencies fall from the most common word to the rarest? Both answers obey strikingly regular mathematical laws, and the laws hold equally for a Victorian novel and for a web crawl. They are Zipf’s law and Heaps’ law, and Chapter 3 is about them.

Those laws explain a good deal of what follows, including why the long tail of rare words never goes away and why the subword tokenisers of Chapter 5 are a practical necessity rather than a nicety. A count also depends on the tokeniser that produced it, so any count you quote should name that tokeniser. Measuring the corpus is the first step towards seeing why the later methods take the shape they do.

Summary

A corpus is the raw material of every method in the book, and the choice of corpus decides what a system can know. Preprocessing sits between the corpus and the model, and each step trades noise for information. Stemming chops suffixes and merges words that should stay apart. Lemmatisation consults a dictionary and returns dictionary words at a price. Case folding and stop word removal lose distinctions that some tasks need, so the right pipeline depends on the task, and modern language models keep almost everything and let the model decide. Minimum edit distance measures how close two strings are, by a dynamic program whose answer depends on the penalties you choose. Finally, the token count, the type count and their ratio describe a corpus, and the way those counts grow is the subject of the next chapter.

Key terms

corpus. a collection of text gathered for study or training.

preprocessing. the transformations applied to raw text before a model sees it.

stemmer. a rule-based tool that strips suffixes without consulting a dictionary.

lemmatiser. a tool that maps a word to its dictionary headword.

lemma. the dictionary headword that a set of word forms belongs to.

subword tokenisation. splitting text into pieces smaller than words, such as the units learned by byte pair encoding.

minimum edit distance. the smallest total cost of insertions, deletions and substitutions that turn one string into another.

penalties. the costs assigned to insertion, deletion and substitution when computing an edit distance.

sequence alignment. matching the elements of two sequences in order, allowing gaps.

token count. the number of word occurrences in a text.

type count. the number of distinct words in a text, also called the vocabulary size.

type-token ratio. the type count divided by the token count.

Further reading.

Manning and Schütze (Manning and Schütze 1999) give a thorough account of corpora, tokenisation and the statistical preprocessing pipeline. Jurafsky and Martin (Jurafsky and Martin 2025) cover text normalisation and its pitfalls with many worked examples. For how modern pretraining data is actually assembled and filtered, the documentation of the web-scale corpora named above remains the best guide.

Practice problems

2.1 The cost of case folding. Give three pairs of English words, other than US and us, that case folding would wrongly merge. For each pair, describe a task where the merge would hurt. If you can, give a task where it would not matter. What does this tell you about calling any preprocessing step “standard”?

2.2 Stemming versus lemmatisation. Take the words better, running, universities and was. Give the output you would expect from a crude stemmer and from a dictionary lemmatiser. Where do the two disagree? Why might a search engine prefer one and a grammar checker the other?

2.3 Corpus statistics by hand. Take the sentence “the cat saw the other cat and the dog”. Count its tokens and its types. Compute the type token ratio. Now append the sentence to itself once and recompute all three. Which number is least stable as the text grows? Why does that foreshadow Heaps’ law in Chapter 3?

2.4 Edit distance by hand. Use the recurrence of Equation (2.1) with the penalties of Equation (2.2). Fill in the full table for sunday to saturday. Box the answer, then trace the path back to the origin as the worked example does. Report the distance and the sequence of edits. Which of the three operations does each step use?

2.5 The penalties change the answer. Redo cat to cart with sub=2\mathrm{sub} = 2 instead of 11, leaving insertion and deletion at 11. Does the distance change? Now do cat to cut under both settings. Explain why the second pair is sensitive to the substitution penalty and the first is not.

2.6 A longer alignment. Compute the edit distance from intention to execution with unit penalties, and then again with sub=2\mathrm{sub} = 2. Trace one cheapest alignment for each setting and say whether the two alignments are the same.

Build and measure

2.7 Stemmer and lemmatiser side by side. Take the first 500 words of any English text. Run the NLTK Porter stemmer and the WordNet lemmatiser over the distinct words. Report how many words each leaves unchanged, how many outputs the stemmer produces that are not English words, and ten words on which the two disagree.

2.8 Implement edit distance. Write a function that returns the Levenshtein distance and one optimal alignment, with the three penalties as parameters. Check it on kitten and sitting, on sunday and saturday, and on the pair of the previous problem. Compare it with nltk.edit_distance, and explain any pair on which the two disagree.

2.9 What each step costs. Before you run anything, predict which of three steps removes the most word types from the Brown corpus, and which removes the most tokens: lowercasing, removing NLTK’s English stop words, and Porter stemming. Then apply the three in turn, reporting the token count and the type count after each. Account for every place your prediction was wrong, and compare your numbers with the table in Chapter 3.

In practice

2.10 The search that cannot find IT. A search team lowercases and stems everything, and users now report that queries for IT support and US law return the wrong documents. Propose the smallest change that fixes both, and describe one test that would have caught the problem before release.

2.11 Near-duplicate listings. A marketplace wants to flag product descriptions that differ only slightly. Decide whether edit distance over characters is the right tool, what would break at a million listings, and what you would use instead for the first filtering step. Say what threshold you would start with and how you would choose a better one.

2.12 A pipeline for contracts. Design a preprocessing pipeline for a tool that searches legal contracts. List the steps you would keep and the ones you would deliberately skip, with a one-line reason for each. Then say what changes if the same documents are fed to a large language model instead. There is no single right answer.

Code for this chapter

Each one reproduces the tables above. Run it in the page, change an input and watch which numbers move.

From Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.