ICS 582Lecture 02Part 01
What counts as a word
Why a word is not a universal unit, the difference between tokens and types, how corpus vocabularies compare, and the preprocessing decisions every tokenizer must make.
- Concepts
- 4
- Slides
- 1-10
- Reading
- 24 min
Why this part matters
Every count, probability, embedding table and cost estimate in NLP starts from a decision about what a unit is. Before a language model can predict the next token, before a retrieval system can index a document, and before Zipf or Heaps can be plotted, someone has to say where one unit ends and the next begins.
This part makes that decision visible. It starts from a sentence that has no single word count, gives you the two definitions every later formula depends on (token and type), reads one famous table of corpus sizes, and finishes with the checklist of preprocessing choices a tokenizer must make. Your research pipeline will fix a tokenization policy once, and every N, |V| and sequence length downstream inherits it. Exams ask for token and type counts under a stated policy and for the consequences of each preprocessing choice.
By the end you can
- State the token and type definitions and compute N and |V| for a given string under a stated policy for case and punctuation.
- Explain why the same sentence has 16 or 18 tokens and 14 or 16 types depending on the policy, and why speech transcripts may keep uh and main-.
- Read the SLP3 corpus table, compute the type to token ratio, and explain both the falling ratio and the Switchboard genre effect.
- Name the four preprocessing decisions and the four ambiguous boundaries, with one downstream consequence each, and state the Penn Treebank convention.
The whole lecture answers one question: what unit does a model operate on, and how do we get from raw bytes to that unit? Everything else is a stop on the way. The roadmap has eight stops, and it is worth holding the shape in mind because the lecture overview page mirrors it exactly.
- Words, with Zipf and Heaps. How to count units, and the two laws that govern how frequency and vocabulary behave as a corpus grows.
- Morphemes. The meaningful parts inside a word, which explain why walk, walks and walked are one lemma but three types.
- Corpora. Where the text comes from, and why genre, domain and time shift every count in this part.
- Unicode. How characters become bytes, so that a tokenizer can promise to represent any script without an unknown symbol.
- Tokenization with BPE. The algorithm that learns its own units from data instead of trusting spaces.
- Sentence segmentation. The period that ends a sentence versus the period inside Dr. or U.S.
- Regular expressions. The pattern language behind pre-tokenizers, cleaners and feature extractors.
- Minimum edit distance. A distance between strings that scores spelling correction and speech recognizers alike.
The first stop carries Zipf's law and Heaps' law. The second is the Morpheme. The third is the Corpus. The fourth turns a Code point into UTF-8 bytes. The fifth is Tokenization and byte-pair encoding. Then come Sentence segmentation, the Regular expression and, finally, Minimum edit distance. This part covers only the opening of the first stop, but it sets the vocabulary every later part reuses.
The seven learning goals on slide 3 map onto the same stops: know why a word is not a universal unit, distinguish types from tokens and explain why vocabulary keeps growing, know what morphemes are, explain Unicode and byte-level processing, describe BPE and tokenizer design choices, use regular expressions, and compute minimum edit distance with dynamic programming. The first two goals are this part.
Recall
Name the eight stops of the lecture roadmap in order.
Count the words in this sentence before reading on: They picnicked by the pool, then lay back on the grass and looked at the stars. Most people say sixteen. Some say eighteen. Both are right, and the reason they can both be right is the subject of this concept.
Worked example
Counting the picnic sentence three ways
Split on spaces
Sixteen pieces: They, picnicked, by, the, pool,, then, lay, back, on, the, grass, and, looked, at, the, stars. The comma and the period ride along inside the pieces they touch.Give punctuation its own place
Cut the comma off pool and the period off stars. Now there are eighteen units. Jurafsky and Martin note that large language models generally count punctuation as separate words, so eighteen is the modern default rather than a quirk.Collapse repeats
the occurs three times. Counting each distinct item once gives fourteen distinct words without punctuation, or sixteen if the comma and the period are counted as distinct items too.Lowercase
Folding They to they changes nothing here, because no other they appears. In another sentence it would merge two distinct items into one.Four answers, one sentence
The sentence never changed. The counting policy did.Policy Tokens N Types |V| Whitespace only 16 14 Punctuation split 18 16 The picnic sentence under two counting policies
In many writing systems spaces suggest boundaries, but a space is only a suggestion. The moment you want a number, you have to decide what to do with everything that a space does not settle, and each decision is tied to what the text is for. Splitting text into units is Tokenization, and the resulting units are tokens. Jurafsky and Martin put it plainly: how we define words depends on the task. The table below pairs each question from the slide with a task that answers yes and a task that answers no.
| Question | A task that says yes | A task that says no |
|---|---|---|
| Is punctuation its own token? | Language models and parsers, where a period or a question mark carries meaning | Bag-of-words retrieval, where punctuation only adds noise |
| Do we lowercase? | Information retrieval, where a query rarely matches the case of the document | Named entity recognition and part-of-speech tagging, where a capital is evidence |
| How do we treat numbers, URLs, emojis, hashtags? | Social media analysis keeps #NLP and emojis whole because they carry sentiment | A grammar checker may replace every number by one placeholder |
| Do we keep disfluencies? | Speech recognition, where uh predicts a restart and identifies the speaker | Parsing and translation, which want the fluent sentence underneath |
Speech: where the units fall apart
Written text at least offers spaces. A transcript of spontaneous speech offers something stranger. Consider the utterance I do uh main- mainly business data processing. There is a broken-off word, main-, which Jurafsky and Martin call a fragment, and a filler, uh, which they call a filled pause. Together these are a Disfluency. Should a tokenizer keep them?
For speech recognition the answer is yes, and for a reason that surprises people: fillers help predict the upcoming word, because they signal that the speaker is restarting the clause or idea, and they are a cue to speaker identification. Clark and Fox Tree went further and argued that uh and um are conventional English words: uh announces an expected minor delay, um a major one. A parser or a translation system, on the other hand, wants the fluent sentence underneath, so it drops them. The Switchboard portion of the Penn Treebank release is explicitly annotated for disfluencies, so this decision is built into a real corpus, not a thought experiment.
Languages with no spaces at all
The space is a convention of some scripts, not of language. Chinese, Japanese and Thai are written without spaces between words, so there is no orthographic word to count. Jurafsky and Martin give a Chinese sentence about Yao Ming reaching the finals and show that its units depend on which standard you adopt. Chinese words average only 1.5 to 1.9 characters, so the character is often the practical unit, and the question "how many words?" simply has no answer until a segmentation standard is chosen.
One Chinese sentence, three counts (SLP3 section 2.1)
- Chinese Treebank standard
- 3 words
- Peking University standard
- 5 words
- Characters
- 7 units
Recall
How many tokens and types does the picnic sentence have without punctuation, and with it?
Recall
Give two reasons Jurafsky and Martin give for keeping uh and um in speech recognition.
Quick check
Which of these is a reason a speech recognizer keeps the filler uh while a parser drops it?
Once a policy is fixed, two numbers describe any text. Take Hamlet's to be or not to be. Six units are written down in order. Only four different ones appear, because to and be each occur twice. Those two numbers have names, and the whole of corpus statistics is built on them.
A Token is one occurrence of a unit in running text, and the total count of tokens is written N. A Type is a distinct vocabulary item, and the number of types is the size of the Vocabulary, written |V|. So to be or not to be has N = 6 tokens and |V| = 4 types: to, be, or, not. The two are tied together by a bookkeeping identity: every token belongs to exactly one type, so the type counts add up to the token count.
Try it yourself. The counter below applies a tokenization policy to a sentence and recomputes both numbers live. Start with the picnic sentence, switch on punctuation splitting and watch N go from 16 to 18. Then load the Apple sentence and flip lowercase: N stays put while |V| drops, because Apple and apple have become one type. That asymmetry is the whole lesson of the next concept in miniature.
16 tokens, 14 types
- They×1
- picnicked×1
- by×1
- the×3
- pool,×1
- then×1
- lay×1
- back×1
- on×1
- grass×1
- and×1
- looked×1
- at×1
- stars.×1
Punctuation and clitic tokens are teal, the <NUM> placeholder is in the accent color. Watch both counts change as you flip each policy.
Five corpora, one table
Jurafsky and Martin collect rough counts for several English corpora, and the lecture reproduces their table. Two columns are on the slide. The two on the right are computed here: types per thousand tokens, and its reciprocal, tokens per type. Read those computed columns first, because they tell a story the raw counts hide.
| Corpus | Genre | Types |V| | Tokens N | Types per 1,000 tokens | Tokens per type |
|---|---|---|---|---|---|
| Shakespeare | Plays and poems | 31 thousand | 884 thousand | 35.1 | 28.5 |
| Brown corpus | 15 written genres, 1961 | 38 thousand | 1 million | 38.0 | 26.3 |
| Switchboard | Telephone conversation | 20 thousand | 2.4 million | 8.3 | 120 |
| COCA | 8 balanced genres | 2 million | 440 million | 4.5 | 220 |
| Google n-grams | Web text | 13 million | 1 trillion | 0.013 | 76,923 |
Down the table, N grows by six orders of magnitude while |V| grows by less than three. The ratio of types to tokens falls from about 35 per thousand for Shakespeare to about 0.013 per thousand for the Google corpus. This is the first preview of Heaps' law: vocabulary grows without bound but sublinearly, |V| = k N^β with β between 0 and 1, and Jurafsky and Martin report values from 0.44 to 0.56 or higher, so vocabulary goes up a little faster than the square root of the text length. Part 02 fits that law properly; here it is enough to see the bend.
Now read across rows instead of down. Brown has one million tokens and 38 thousand types. Switchboard has more than twice as many tokens and only 20 thousand types, fewer even than Shakespeare with a third of Switchboard's tokens. Size alone cannot explain that. Switchboard is about 2,400 telephone conversations among 543 speakers on about 70 everyday topics, and casual conversation reuses a small everyday vocabulary. Brown samples 500 texts across 15 written genres, and Shakespeare's plays reach for coinages and archaic forms. This is the point of slide 6: even within one language, genre and domain shift the vocabulary, so |V| depends on the Corpus, not only on N.
Why the vocabulary never stops growing
The falling ratio and the endless growth have the same cause. Function words like the and of are seen early and then only repeat. Content words keep arriving. Slide 8 lists where they come from, and each source is a reason your model will meet a word it has never seen.
- Proper names and new products: every person, place, company and gadget is a type, and new ones appear every day.
- Creative spellings and typos: cooool, gr8 and every misspelling is a fresh type under a wordform policy.
- Code-switching: speakers mix languages within one utterance, so an English corpus carries Spanish, Hindi or Arabic types as well.
- Morphology: walk, walks, walked and walking are four wordform types but one Lemma. Inflection multiplies surface forms, and morphologically rich languages multiply them far more.
- Compounding and multiword expressions: New York and ice cream behave as single lexical units but span a space. Sag and colleagues called multiword expressions a pain in the neck for NLP, and Jurafsky and Martin note that tokenizing them needs a dictionary and is tied up with named entity recognition.
The consequence is that out-of-vocabulary words are unavoidable under any word-level policy. However large the training corpus, tomorrow's text contains a name or a typo that is not in V. That is the problem subword tokenization solves later in this lecture, by building rare words out of pieces that are in the vocabulary.
Recall
Define token and type, then give N and |V| for 'to be or not to be'.
Recall
Why does Switchboard have fewer types than Shakespeare despite almost three times as many tokens?
Quick check
Counting punctuation as tokens and ignoring case, what are N and |V| for 'to be, or not to be.'?
Quick check
Switchboard has almost three times Shakespeare's tokens but fewer types. What explains this?
Quick check
The vocabulary size |V| of a model is best described as a property of which of these?
Every policy in this part has been described in words. Here is one written down as rules and run on a real sentence. The Penn Treebank convention is the standard for parsed corpora of English, and Jurafsky and Martin use this example to show its output.
Worked example
Penn Treebank tokenization of one sentence
Input
"The San Francisco-based restaurant," they said, "doesn't charge $10".Separate all punctuation
Each quotation mark, comma and the final period becomes its own token, so restaurant," turns into restaurant, , and ".Keep hyphenated words together
Francisco-based stays one token. The convention treats a hyphenated compound as a unit.Split clitics
doesn't becomes does and n't. Marcus and colleagues describe this in the original Treebank paper: contractions and the Anglo-Saxon genitive of nouns are automatically split into their component morphemes, so children's becomes children and 's, and won't becomes the odd pair wo and n't.Separate the currency sign
$10 becomes $ and 10.Output
" The San Francisco-based restaurant , " they said , " does n't charge $ 10 " . That is N = 18 tokens and |V| = 14 types, because the four quotation marks are one type and the two commas are one type.
The four decisions
The worked example silently made four decisions, and slide 9 names them. Each has options, each helps some task and each hurts another. The table is the answer to the exam question "list four preprocessing decisions and one downstream consequence of each".
| Decision | Options | Helps | Hurts |
|---|---|---|---|
| Case folding | Keep case, lowercase everything, or truecase | Retrieval recall: a query for apple matches Apple | Named entity recognition: Apple, Bush, the Fed and General Motors lose their capital evidence |
| Punctuation | Attach to the word, separate it, or drop it | Parsers and sentence segmenters, which read commas and periods as structure | Dropping loses question marks and quotes; naive splitting breaks m.p.h., Ph.D., $45.55 and 01/02/06 |
| Normalization | Accents, precomposed versus decomposed letters, curly versus straight quotes, hyphen versus dash | Matching and a compact vocabulary: one quote type, not four | Meaningful distinctions vanish, such as accented pairs in French or a minus sign versus a hyphen |
| Numbers | Keep raw, map to <NUM>, or segment into digit chunks | <NUM> shrinks |V|; digit chunks let a model generalize arithmetic | Raw numbers make every price a new type; <NUM> throws away magnitude |
Case folding is the most tempting shortcut. Manning, Raghavan and Schütze observe that for information retrieval, lowercasing everything often remains the most practical solution, and in the same breath list what it destroys: proper nouns distinguished only by case, such as General Motors, the Fed against fed, and Bush against bush. Their alternative is truecasing, restoring the likely original case with a classifier. Jurafsky and Martin add that for other tasks capitalization is a useful feature and is retained, so some teams keep a cased and an uncased model side by side.
Normalization is the quiet one. A Unicode normalization form decides whether the precomposed letter Ç at U+00C7 and the sequence C plus combining cedilla are the same type. Unicode Standard Annex 15 defines four forms, NFC, NFD, NFKC and NFKD, and the same logic applies to four kinds of quotation mark and three kinds of dash that a keyboard and a word processor scatter through any corpus. Skip it and your vocabulary silently holds several copies of the same word.
Numbers show the trade-off most sharply. Kept raw, every price and every year is a new type and |V| explodes. Mapped to a single <NUM> placeholder, the vocabulary shrinks but the model can no longer tell 12 from 12,000. Modern tokenizers pick a middle path: Jurafsky and Martin describe the GPT-4o tokenizer chunking numbers into groups of up to three digits, so magnitude survives as a sequence of small pieces.
The four ambiguous boundaries
Even after the four decisions are made, some characters refuse to settle. Slide 10 collects them. In each case the same character is a boundary in one context and part of a unit in another, and a tokenizer has to pick a default and accept the errors it causes.
| Boundary | Example | Treebank default | Alternative |
|---|---|---|---|
| Hyphens | state-of-the-art | Keep the hyphenated word together as one token | Split into state, of, the, art so each piece is a known type |
| Abbreviations | U.S., Dr., e.g. | Keep the internal periods; the trailing period is ambiguous with a sentence end | Strip periods entirely, at the cost of merging US the country with us the pronoun |
| Clitics | we'll, I'm, possessive 's | Split off the clitic: we 'll, I 'm, children 's, does n't, wo n't | Keep the contraction whole, so doesn't and does not are unrelated types |
| Social media | #NLP, @user, URLs | Splits # and @ off their word and breaks a URL at its colon, slashes and question mark | A social-media tokenizer keeps hashtags, handles and URLs whole with dedicated patterns |
A Clitic is the trickiest of the four because the apostrophe is three-way ambiguous. Jurafsky and Martin point out that it marks the genitive (the book's cover), quotation ('The other class', she said) and the contracted clitic (we'll, I'm). Hyphens run from co-education, where the pieces are meaningless alone, to Hewlett-Packard, where each is a name, and Manning and colleagues show there is no rule that suits both. Abbreviation periods will return as the central problem of Sentence segmentation later in the lecture. Social media adds hashtags, handles and URLs that should be kept whole, since #NLP or a web address split at its punctuation is worthless. A Treebank-style tokenizer will not do this by itself: it pads # and @ with spaces and breaks a URL at its colon, so a social-media pipeline adds hashtag, handle and URL patterns in front of it.
Recall
Under the Penn Treebank convention, tokenize 'doesn't' and 'children's'.
Quick check
Which preprocessing decision helps information retrieval but hurts named entity recognition?
Recap
If you remember nothing else
- A word is not a natural unit: the picnic sentence has 16 or 18 tokens and 14 or 16 types depending on the punctuation policy.
- Token = one occurrence (N); type = one distinct item (|V|); 'to be or not to be' is N = 6, |V| = 4.
- Speech adds fragments (main-) and filled pauses (uh, um); speech recognizers keep them, parsers drop them.
- Chinese, Japanese and Thai have no orthographic words; the same Chinese sentence can be 3, 5 or 7 units.
- Types grow with tokens but sublinearly (Heaps: |V| = k N^beta, beta about 0.5); the type to token ratio falls from 3.5% (Shakespeare) to 0.0013% (Google n-grams).
- Genre matters as much as size: Switchboard has 2.4 million tokens but only 20 thousand types.
- Vocabulary is hard because of names, new products, typos, code-switching, morphology and multiword expressions; OOV is unavoidable.
- Four preprocessing decisions: case folding, punctuation, normalization, numbers. Four ambiguous boundaries: hyphens, abbreviations, clitics, social media.
- Penn Treebank convention: separate punctuation, keep hyphenated words, split clitics and possessives (doesn't -> does n't, children's -> children 's).
- |V| is a property of the corpus plus the tokenization policy, never of the language alone.
Sources
- Speech and Language Processing, 3rd edition draft, chapter 2: Words and TokensBookJurafsky and Martin, StanfordDraft of August 19, 2026. Sections 2.1 (words, types, Fig. 2.1, Heaps), 2.5 (corpora), 2.8 (Penn Treebank tokenization)(opens in a new tab)
- Words and Tokens lecture slidesDocsJurafsky and Martin, StanfordSource of the 31 thousand Shakespeare figure reproduced on slide 7(opens in a new tab)
- Building a Large Annotated Corpus of English: The Penn TreebankPaperComputational Linguistics 19(2), 1993, Marcus, Santorini and MarcinkiewiczFootnote 8: contractions and the genitive split into component morphemes(opens in a new tab)
- nltk.tokenize.treebank: TreebankWordTokenizerDocsNLTK Projectdon't becomes do n't, punctuation separated(opens in a new tab)
- Introduction to Information Retrieval, section 2.2.1: TokenizationBookManning, Raghavan and Schütze, Cambridge University PressToken and type definitions, O'Neill, hyphens from co-education to Hewlett-Packard(opens in a new tab)
- Introduction to Information Retrieval, section 2.2.3: Capitalization and case-foldingBookManning, Raghavan and Schütze, Cambridge University PressGeneral Motors, the Fed, Bush; truecasing; lowercasing remains the most practical solution for IR(opens in a new tab)
- Using uh and um in spontaneous speakingPaperCognition 84(1), 2002, Clark and Fox Treeuh signals a minor delay, um a major one; both are conventional English words(opens in a new tab)
- Multiword Expressions: A Pain in the Neck for NLPPaperCICLing 2002, Sag, Baldwin, Bond, Copestake and FlickingerWords with spaces such as San Francisco as one analysis of multiword expressions(opens in a new tab)
- Switchboard-1 Release 2DocsLinguistic Data Consortium, LDC97S62About 2,400 two-sided telephone conversations, 543 speakers, about 70 topics(opens in a new tab)
- Treebank-3DocsLinguistic Data Consortium, LDC99T42The Switchboard portion is dysfluency-annotated(opens in a new tab)
- Web 1T 5-gram Version 1, readmeDocsLinguistic Data Consortium, LDC2006T131,024,908,267,229 tokens, 13,588,391 unigrams; unigram cutoff 200, n-gram cutoff 40(opens in a new tab)
- Natural Language Processing with Python, chapter 2: Accessing Text CorporaBookBird, Klein and Loper, NLTK ProjectBrown corpus: 1961, 500 sources, 15 genres, the first million-word electronic corpus(opens in a new tab)
- Unicode Standard Annex #15: Unicode Normalization FormsDocsUnicode ConsortiumNFC, NFD, NFKC, NFKD; canonical equivalence of U+00C7 and C plus combining cedilla(opens in a new tab)
- Corpus of Contemporary American English (COCA)DocsEnglish-Corpora.orgThe 440 million figure is the older size SLP3 uses; the current corpus is about 1 billion words, 1990 to 2019(opens in a new tab)