Majid Al-RaimiWhat counts as a word

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
Understood
0/4 concepts

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

  1. State the token and type definitions and compute N and |V| for a given string under a stated policy for case and punctuation.
  2. 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-.
  3. Read the SLP3 corpus table, compute the type to token ratio, and explain both the falling ratio and the Switchboard genre effect.
  4. 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.

  1. Words, with Zipf and Heaps. How to count units, and the two laws that govern how frequency and vocabulary behave as a corpus grows.
  2. Morphemes. The meaningful parts inside a word, which explain why walk, walks and walked are one lemma but three types.
  3. Corpora. Where the text comes from, and why genre, domain and time shift every count in this part.
  4. Unicode. How characters become bytes, so that a tokenizer can promise to represent any script without an unknown symbol.
  5. Tokenization with BPE. The algorithm that learns its own units from data instead of trusting spaces.
  6. Sentence segmentation. The period that ends a sentence versus the period inside Dr. or U.S.
  7. Regular expressions. The pattern language behind pre-tokenizers, cleaners and feature extractors.
  8. 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.

Words (Zipf and Heaps), morphemes, corpora, Unicode, tokenization (BPE), sentence segmentation, regular expressions, minimum edit distance.

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

  1. 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.
  2. 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.
  3. 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.
  4. Lowercase

    Folding They to they changes nothing here, because no other they appears. In another sentence it would merge two distinct items into one.
  5. Four answers, one sentence

    PolicyTokens NTypes |V|
    Whitespace only1614
    Punctuation split1816
    The picnic sentence under two counting policies
    The sentence never changed. The counting policy did.
The picnic sentence segmented by a punctuation-aware policy: seventeen boundaries, the three teal ones isolating the comma and the period, giving 18 tokens and 16 types

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.

QuestionA task that says yesA task that says no
Is punctuation its own token?Language models and parsers, where a period or a question mark carries meaningBag-of-words retrieval, where punctuation only adds noise
Do we lowercase?Information retrieval, where a query rarely matches the case of the documentNamed 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 sentimentA grammar checker may replace every number by one placeholder
Do we keep disfluencies?Speech recognition, where uh predicts a restart and identifies the speakerParsing and translation, which want the fluent sentence underneath
Tokenization questions and the tasks that answer them differently

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?

16 tokens and 14 types without punctuation (the occurs three times); 18 tokens and 16 types once the comma and the period count as tokens.

Recall

Give two reasons Jurafsky and Martin give for keeping uh and um in speech recognition.

They 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 add that uh signals a minor delay and um a major one.

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.

N=wVc(w)N = \sum_{w \in V} c(w)
Tokens are the sum of type counts: 2 + 2 + 1 + 1 = 6
Six tokens in running order collapse into four type stacks: to and be twice each, or and not once, and the stack heights add back up to N = 6

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.

InteractiveToken and type counter: every toggle is a tokenization policy
Tokens N16occurrences
Types |V|14distinct
|V| / N0.88types per token

16 tokens, 14 types

Token stream
Theypicnickedbythepool,thenlaybackonthegrassandlookedatthestars.
Type set with counts
  • 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.

CorpusGenreTypes |V|Tokens NTypes per 1,000 tokensTokens per type
ShakespearePlays and poems31 thousand884 thousand35.128.5
Brown corpus15 written genres, 196138 thousand1 million38.026.3
SwitchboardTelephone conversation20 thousand2.4 million8.3120
COCA8 balanced genres2 million440 million4.5220
Google n-gramsWeb text13 million1 trillion0.01376,923
Rough numbers of wordform types and tokens for English corpora (SLP3 Fig. 2.1 and the lecture slide), with computed ratios

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.

Types against tokens with both axes on a log scale: Heaps' law is a straight line of slope about 0.5, well under the slope-1 line where every token would be new, and Switchboard sits below the fit because conversation reuses a small vocabulary

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'.

A token is one occurrence of a unit in running text, and N counts them. A type is a distinct vocabulary item, and |V| counts them. N = 6, |V| = 4 (to, be, or, not).

Recall

Why does Switchboard have fewer types than Shakespeare despite almost three times as many tokens?

Genre and domain. Conversational telephone speech reuses a small everyday vocabulary, so |V| depends on the corpus and its genre, not only on N.

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

  1. Input

    "The San Francisco-based restaurant," they said, "doesn't charge $10".
  2. Separate all punctuation

    Each quotation mark, comma and the final period becomes its own token, so restaurant," turns into restaurant, , and ".
  3. Keep hyphenated words together

    Francisco-based stays one token. The convention treats a hyphenated compound as a unit.
  4. 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.
  5. Separate the currency sign

    $10 becomes $ and 10.
  6. 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.
Two Penn Treebank splits: a tick drops between does and n't and between children and 's, then the halves slide apart, matching footnote 8 of Marcus, Santorini and Marcinkiewicz

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".

DecisionOptionsHelpsHurts
Case foldingKeep case, lowercase everything, or truecaseRetrieval recall: a query for apple matches AppleNamed entity recognition: Apple, Bush, the Fed and General Motors lose their capital evidence
PunctuationAttach to the word, separate it, or drop itParsers and sentence segmenters, which read commas and periods as structureDropping loses question marks and quotes; naive splitting breaks m.p.h., Ph.D., $45.55 and 01/02/06
NormalizationAccents, precomposed versus decomposed letters, curly versus straight quotes, hyphen versus dashMatching and a compact vocabulary: one quote type, not fourMeaningful distinctions vanish, such as accented pairs in French or a minus sign versus a hyphen
NumbersKeep raw, map to <NUM>, or segment into digit chunks<NUM> shrinks |V|; digit chunks let a model generalize arithmeticRaw numbers make every price a new type; <NUM> throws away magnitude
Preprocessing decisions with their options and consequences

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.

BoundaryExampleTreebank defaultAlternative
Hyphensstate-of-the-artKeep the hyphenated word together as one tokenSplit into state, of, the, art so each piece is a known type
AbbreviationsU.S., Dr., e.g.Keep the internal periods; the trailing period is ambiguous with a sentence endStrip periods entirely, at the cost of merging US the country with us the pronoun
Cliticswe'll, I'm, possessive 'sSplit off the clitic: we 'll, I 'm, children 's, does n't, wo n'tKeep the contraction whole, so doesn't and does not are unrelated types
Social media#NLP, @user, URLsSplits # and @ off their word and breaks a URL at its colon, slashes and question markA social-media tokenizer keeps hashtags, handles and URLs whole with dedicated patterns
Ambiguous boundaries, the Penn Treebank default and the alternative

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'.

does + n't, and children + 's. Contractions and the genitive are split into their component morphemes; punctuation is separated; hyphenated words stay together.

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