Words and Tokens
Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2
127 cards
Introduction
- How did ELIZA produce its responses?By simple pattern matching on words: it recognized phrases like “I need X” and transformed them into outputs like “What would it mean to you if you got X?”, imitating a Rogerian psychotherapist.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, Introduction, p. 33
- What is tokenization?Separating out (tokenizing) words and word parts from running text: the first step in modern NLP.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, Introduction, p. 33
- What is edit distance, and where does NLP use it?A measure of how similar two strings are, based on the number of insertions, deletions and substitutions needed to turn one into the other. It is used whenever strings must be compared, e.g. in the word error rate metric for speech recognition.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, Introduction, p. 33
2.1 Words
- Should punctuation count as words?It depends on the task. Punctuation marks boundaries (commas, periods, colons) and some meaning (question marks, quotation marks). LLMs generally treat punctuation as separate words.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.1, p. 34
- What is an utterance?The spoken correlate of a sentence.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.1, p. 34
- What are the two kinds of disfluency in “I do uh main- mainly business data processing”?A fragment (the broken-off word main-) and a filled pause or filler (uh).
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.1, p. 34
- Why might a speech recognizer keep fillers like uh and um as words?They help predict the upcoming word, since they may signal that the speaker is restarting a clause or idea. They can also be a cue to speaker identity.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.1, p. 34
- What is the difference between word types and word instances?Types are the distinct words in a corpus (their number is the vocabulary size \(|V|\)); instances are the running words, \(N\). “The cat saw the dog” has 5 instances but 4 types.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.1, p. 34
- Why does the book avoid calling word instances “word tokens”?It reserves “token” for the output of subword tokenization algorithms.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.1, p. 34
- Should They and they be the same word type?It depends on the task: they may be merged where formatting doesn’t matter, but capitalization is a useful feature for other tasks. Sometimes both cased and uncased versions of a model are kept.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.1, p. 34
- Why is the orthographic word I’m really two grammatical words?It functions as the subject pronoun I plus the verb ’m (short for am).
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.1, p. 35
- Which writing systems have no orthographic words, and why is that a problem?Chinese, Japanese and Thai don’t use spaces to mark word boundaries, so deciding what counts as a word requires a (debatable) standard.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.1, p. 35
- What is a Chinese character called, and what does it usually correspond to?A hanzi. Each character generally represents a single morpheme and is pronounced as a single syllable.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.1, p. 35
- How can the Chinese sentence “Yao Ming reaches the finals” be segmented into 3, 5 or 7 units?3 words under the Chinese Treebank standard (names are one word: YaoMing / reaches / finals); 5 under the Peking University standard (Yao / Ming / reaches / overall / finals); or 7 characters if words are ignored entirely.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.1, p. 35
- Why can characters serve as basic units for Chinese but not for Japanese or Thai?Chinese characters are at a reasonable semantic level (roughly morphemes) for most applications; in Japanese and Thai the individual character is too small a unit.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.1, p. 35
- State Herdan’s Law (Heaps’ Law).The number of word types grows with the number of instances as \(|V| = kN^{\beta}\), with constants \(k > 0\) and \(0 < \beta < 1\). Roughly, vocabulary grows a bit faster than the square root of text length.
New word types keep appearing, ever more slowly, but never stop. - Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.1, p. 36
- How do function words and content words behave differently as a corpus grows?Function words (a, of) form a roughly fixed set that is exhausted early. Content words, especially nouns such as names and technical terms, keep growing indefinitely. So vocabulary growth has two regimes, with different \(\beta\) values.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.1, p. 36
- Why does Herdan’s Law cause a problem for computational models?No vocabulary, however big, contains every word that might occur, so models constantly meet unknown words they have never seen before.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.1, p. 36
- What two problems make words a poor unit of processing for NLP models?Many languages lack orthographic words, and defining them post hoc is hard; and the number of words grows without bound. So models use smaller subword units that can be recombined into unseen words.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.1, p. 37
2.2 Morphemes: parts of words
- What is a morpheme? What is morphology?A morpheme is a minimal meaning-bearing unit of language (cats = cat + plural -s). Morphology is the study of morphemes.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.2, p. 37
- What is the difference between a root and an affix?The root is the central morpheme that supplies the main meaning (work in worked); affixes add additional meanings (-ed).
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.2, p. 37
- How do inflectional morphemes differ from derivational morphemes?Inflectional morphemes are grammatical, play a syntactic role such as agreement or tense (plural -s, past -ed), are productive, often obligatory and predictable in meaning. Derivational morphemes are idiosyncratic, apply to specific word subclasses, usually change the word class, and have less predictable meanings (care → careful → carefully).
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.2, p. 37
- What is a clitic? Give examples.A morpheme that acts syntactically like a word but is reduced and attached to another word, so it cannot stand alone: English ’ve in I’ve, possessive ’s, French l’ in l’opéra, Arabic b ‘by/with’ and w ‘and’.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.2, p. 37
- What is morphological typology?The study of how languages vary in their morphology, i.e. how words break up into parts.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.2, p. 38
- What is the morphemes-per-word dimension of morphological typology?A scale from isolating (analytic) languages with about one morpheme per word (Vietnamese, Cantonese), through synthetic languages, to polysynthetic languages where one word can express a whole English sentence (Koryak).
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.2, p. 38
- What is the agglutinative–fusional dimension of morphological typology?How easily morphemes can be segmented: agglutinative languages (Turkish) have morphemes with clean boundaries; fusion languages (Russian) have affixes that conflate several categories, e.g. -om in stolom marks instrumental + singular + first declension at once.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.2, p. 38
- Why is the English -s in “She reads” an example of fusion?The single suffix means both third person singular and present tense, with no way to divide the meaning between parts.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.2, p. 38
- Are labels like “agglutinative” or “polysynthetic” properties of whole languages?More accurately they are general tendencies: a language can use different morphological systems.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.2, p. 39
- Why are morphemes not used as a standard for cross-lingual tokenization?Morphemes can be hard to define, and many languages have complex fused morphemes that aren’t easy to break into pieces.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.2, p. 39
2.3 Unicode
- What is Unicode?A standard for representing text written in any character of any script of the world’s languages (including dead languages like Sumerian cuneiform and invented ones like Klingon), plus symbols, emoji, etc.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.3, p. 39
- What is ASCII, and how does it relate to Unicode?The 1960s American Standard Code for Information Interchange: one byte per character, using only 128 values (high-order bit 0), for the Latin characters used in English. It survives as Unicode’s first block (“Basic Latin”).
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.3, p. 39
- Why is ASCII insufficient?Even Latin-script languages need characters outside it (Spanish ñ, ó), and many languages use other scripts entirely (Devanagari, Chinese characters…).
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.3, p. 39
- What is a Unicode code point?A unique abstract id for a character, a number from 0 to 0x10FFFF, written with the prefix U+ (e.g. U+0061 for a).
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.3, p. 40
- Why do the first 128 Unicode code points match ASCII?Unicode was designed to be backwards compatible with ASCII.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.3, p. 40
- What is the difference between a code point and a glyph?A code point is the abstract character; a glyph is its visual representation, stored in a typeface. a in Times, Courier, bold or italic is the same code point U+0061.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.3, p. 40
- What is a character encoding?The way a character (code point) is actually written as bytes in a text string or file. UTF-8 is by far the most frequent; almost the whole web uses it.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.3, p. 40
- Why don’t we store text as raw 4-byte code points (UTF-32)?It makes files 4 times longer than ASCII and full of zero bytes, and zero bytes break ASCII-based systems that historically used 0 as an end-of-string marker.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.3, p. 41
- What does it mean that UTF-8 is a variable-length encoding?Characters take different numbers of bytes: ASCII characters take 1 byte, other code points 2, 3 or 4 bytes. Each multi-byte byte is between 128 and 255, and the first byte’s leading bits say how many bytes follow.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.3, p. 41
- Show how UTF-8 packs code points into bytes.
The code point’s bits fill the x, y, z, u slots.code points bytes U+0000–007F 0xxxxxxxU+0080–07FF 110yyyyy 10xxxxxxU+0800–FFFF 1110zzzz 10yyyyyy 10xxxxxxU+10000–10FFFF 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.3, p. 41
- How is ñ (U+00F1) encoded in UTF-8?It is in the U+0080–07FF range, so it takes 2 bytes: its bits
00011 110001fill110yyyyy 10xxxxxx, giving11000011 10110001= 0xC3 0xB1.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.3, p. 41
- Roughly how many UTF-8 bytes do characters of different scripts need?ASCII: 1 byte; most other European, Middle Eastern and African scripts: 2 bytes; most Chinese, Japanese and Korean characters: 3 bytes; rarer CJKV characters, emoji and some symbols: 4 bytes.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.3, pp. 41–42
- What are the advantages of UTF-8?It is efficient for common characters, uses no zero bytes (except for NULL itself), is backwards compatible with ASCII (ASCII files are valid UTF-8), and is self-synchronizing: after corruption you can find the next or previous character start by moving at most 3 bytes.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.3, p. 42
- In Python 3, what does
len()of a string count?Code points (characters), not bytes: Python 3 strings are sequences of Unicode code points. Bytes appear only when encoding/decoding to a file.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.3, p. 42
- Is there such a thing as a plain text file without an encoding?No. Every file is in some encoding (UTF-8 or older ones like ASCII or Latin-1), which must be specified when reading or writing.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.3, p. 42
2.4 Subword tokenization: byte-pair encoding
- What are the pros and cons of words, morphemes and characters as tokens?Words and morphemes are at roughly the right level (consistent meanings) but hard to define formally. Characters are easy to define but too small a unit.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.4, p. 42
- Why tokenize text into a fixed set of units at all?So systems can agree on basic questions (How long is this text? Is New York one token or two?), which is essential for replicability; metrics like perplexity assume a fixed tokenization. Subword tokens also eliminate unknown words.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.4, p. 42
- What is the unknown word problem, and how do subwords solve it?A system trained on low, new, newer but not lower wouldn’t know what to do with lower at test time. With subword tokens, every unseen word can be built from known pieces (low + er), in the worst case from single characters.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.4, p. 42
- What two subword tokenization algorithms are widely used in modern LMs?Byte-pair encoding (BPE; Sennrich et al., 2016) and the unigram language model (ULM; Kudo, 2018). The SentencePiece library implements both.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.4, p. 43
- What are the two phases of a tokenization scheme like BPE?A training phase, which induces a vocabulary of tokens from a raw training corpus, and an encoding phase, which segments new text into tokens from that vocabulary.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.4, p. 43
- Describe the BPE training algorithm.Start with a vocabulary of all single characters (or bytes). Repeatedly find the most frequent pair of adjacent tokens in the corpus, add their concatenation as a new token, and replace every occurrence of the pair with it. Stop after \(k\) merges; the vocabulary is the characters plus \(k\) new tokens.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.4, p. 43
- Run two BPE merges on the corpus
A B D C A B E C A B.Most frequent pair:A B→ new token AB:AB D C AB E C AB. Next most frequent:C AB→ CAB:AB D CAB E CAB. Vocabulary is now {A, B, C, D, E, AB, CAB}.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.4, p. 43
- Why does BPE usually not merge across word boundaries?The corpus is first pre-split at whitespace and punctuation (with regexes) into words with counts; merges are allowed only inside these strings, which keeps tokens word-like.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.4, p. 43
- In BPE training on new, renew, reset, set, which prefix does the algorithm “discover”, and how?re-: after merging
n eandne w, frequent pairs like (space, r) and then (r, e) merge into a word-initial token “␣re”, since it appears in renew and reset.merge corpus afterwards n e→ner e ne w,r e s e tne w→newr e new,r e s e t␣ r→␣r␣r e new,␣r e s e t␣r e→␣re␣re new,␣re s e t- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.4, p. 44
- How does the BPE encoder tokenize a test sentence?It splits each word into characters, then applies the learned merges greedily in the order they were learned (most frequent in training first). Test-data frequencies play no role.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.4, p. 45
- Besides recreating training words, what useful units does BPE learn?Morpheme-like pieces, e.g. the prefix re- (for unseen revisit, rearrange) or word-internal new without a leading space (for anew).
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.4, p. 45
- What vocabulary sizes do real BPE tokenizers use, and what is the effect?Tens of thousands of merges, giving 50,000–200,000 tokens, so most (English) words are single tokens and only rare or unknown words are split.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.4, p. 45
- On what units is BPE usually run for Unicode text, and why?On the individual bytes of the UTF-8 encoding. Only 256 byte values exist, so there are no unknown tokens; BPE first rediscovers common multi-byte UTF-8 sequences. Rare illegal byte sequences can be filtered.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.4, p. 45
- What regularities show up in an industrial BPE tokenizer’s output for English?Most words are single tokens, usually including their leading space; clitics like ’s split off rare names but not frequent words like she’s; numbers are chunked into groups of 3 digits; capitalization and position change segmentation (Any+how vs ␣anyhow).
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.4, p. 46
- What is pretokenization?A stage before BPE that segments the input with regular expressions: breaking at spaces and punctuation, splitting off clitics, and chunking numbers.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.4, p. 46
- What do SuperBPE and BoundlessBPE do differently?After learning ordinary subword tokens with pretokenization, they run a second BPE stage that allows merges across spaces and punctuation, producing larger multi-word tokens that encode text more efficiently.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.4, p. 46
- Why do multilingual BPE tokenizers oversegment languages other than English?Training data is dominated by English, so most tokens are spent on English; other languages get split into shorter pieces (Spanish hondo → h + ondo), and lower-resource languages sometimes down to single characters.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.4, p. 46
- What problems does oversegmentation into tiny tokens cause?Poorer representations of meaning, the need for longer contexts, and higher costs to train (and use) models for those languages.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.4, p. 47
2.5 Corpora
- Why should NLP algorithms be tested on more than English?Algorithms should work across languages with different properties; developing and testing only on English (or a few big national languages) excludes most of the world’s roughly 7,000 languages.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.5, p. 47
- What are AAE and MAE, and why do they matter for tokenization?African American English and Mainstream American English. AAE features such as iont (MAE I don’t) or talmbout (talking about) affect word segmentation, so tools must handle such varieties.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.5, p. 47
- What is code switching?Using multiple languages within a single utterance, e.g. Spanish–English or Hindi–English mixing in social media posts. It is very common worldwide.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.5, p. 47
- What are vernacular and vehicular languages?Speakers of mainly oral languages are often diglossic: an oral vernacular for family and local communication, and a vehicular language, usually written, for the wider economy, society or state.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.5, p. 47
- Besides language, what dimensions of variation shape a corpus?Genre (news, fiction, Wikipedia, conversation, legal or medical text…), the demographics of writers/speakers (age, gender, race, class), and time (language changes).
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.5, pp. 47–48
- What is a datasheet (or data statement) for a corpus?Documentation by the corpus creator of its motivation, situation, language variety, speaker demographics, collection process (size, sampling, consent, preprocessing), annotation process, and distribution (copyright/IP restrictions).
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.5, p. 48
2.6 Regular expressions
- What is a regular expression, formally and practically?Formally, an algebraic notation for characterizing a set of strings. Practically, a pattern language for searching text and specifying changes to it; used in grep, editors, every programming language, and BPE pretokenization.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 48
- What does Python’s
re.search(pattern, string)return?The first match of the pattern inside the string.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 48
- Why are regexes in Python usually written as raw strings,
r"..."?In raw strings backslashes are treated literally, so regex escapes like\bor\dreach the regex engine unchanged.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 48
- What do square brackets do in a regex? Give examples.Character disjunction: match any one of the characters inside.
[mM]arymatches Mary or mary;[abc]matches a, b or c.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 49
- What does a dash inside brackets mean, as in
[b-g]?A range: any one character from b to g.[A-Z]is an uppercase letter,[0-9]a digit.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 49
- What does
[^a]mean, and when does^inside brackets mean something else?Any single character except a. The caret negates only when it is the first symbol after[; elsewhere (e.g.[e^]) it is a literal caret.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 49
- What does
?mean in a regex? Give an example.Zero or one occurrence of the previous character or expression:colou?rmatches color and colour.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 50
- What is the difference between the Kleene
*and Kleene+?*means zero or more occurrences of the preceding character or expression;+means one or more.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 50
- Write a regex for the sheep language baa!, baaa!, baaaa!, …, and say why
ba*!fails.baa+!(orbaaa*!).ba*!would also match b! and ba!, since*allows zero as.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 50
- Why is an integer written
[0-9]+rather than[0-9]*?[0-9]*also matches the empty string.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 50
- What do
{3}and.mean in a regex?{3}: exactly 3 occurrences of the previous character or expression (ax{10}z)..: a wildcard matching any single character except newline.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 50
- Write a regex to find lines in which the word rose appears twice.
rose.*rose:.*matches any string of zero or more characters between them.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 50
- What are anchors? What do
^and$match?Special characters that tie a match to a place in the string:^matches the start of a line,$the end.^The dog\.$matches a line containing only “The dog.”.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, pp. 50–51
- What are the three uses of the caret
^?Start of line (anchor), negation as the first symbol inside square brackets, and a literal caret.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, pp. 50–51
- What do
\band\Bmatch? Will\b99\bmatch in “299” and in “$99”?\bis a word boundary,\Ba non-boundary, where a “word” is a run of letters, digits or underscores. It won’t match inside 299 (99 follows a digit), but will match $99 ($ is not a word character).- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 51
- What does it mean that anchors and
\bare zero-width?They match the empty string at a position without consuming characters, so the following characters remain available to match.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 51
- Why can’t
[catdog]find “cat or dog”, and what should you write?Brackets match a single character from the set. Use the disjunction (pipe) operator:cat|dog.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, pp. 51–52
- Why doesn’t
guppy|iesmatch both guppy and guppies, and how is it fixed?Sequences bind tighter than|, so it means guppy or ies. Use parentheses:gupp(y|ies).- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 52
- Why does
Column [0-9]+ *not match repeated column labels, and how do you fix it?The*applies only to the preceding space. Group the whole sequence:(Column [0-9]+ +)*.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 52
- Give the regex operator precedence hierarchy, from highest to lowest.Parentheses
()> counters* + ? {}> sequences and anchors > disjunction|. Sothe*matches theeee (not thethe), andthe|anymatches the or any.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 52
- What does it mean that regex matching is greedy, and how do you get non-greedy matching?Patterns match the largest string they can (
[a-z]*on “once upon” matches once). The non-greedy operators*?and+?match as little as possible.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 52
- Refine a regex for the article the step by step.
themisses sentence-initial The →[tT]he, which wrongly matches inside other or there →\b[tT]he\b.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, pp. 52–53
- What are false positives and false negatives in pattern matching, and which measures do they correspond to?False positives are strings incorrectly matched (other); false negatives are strings incorrectly missed (The). Minimizing false positives increases precision; minimizing false negatives increases recall. The two efforts pull against each other.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 53
- What do
\d,\wand\s(and their capitals) match?\da digit,\wan alphanumeric character or underscore,\swhitespace.\D,\W,\Sare their complements.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 53
- How do you match a literal period, star or bracket?Escape it with a backslash:
\.,\*,\[,\\.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 53
- What are capture groups? Use one to convert US dates (mm/dd/yyyy) to dd-mm-yyyy.Parentheses store what they matched in numbered groups that can be referred to as
\1,\2…re.sub(r"(\d{2})/(\d{2})/(\d{4})", r"\2-\1-\3", s)turns 10/15/2011 into 15-10-2011.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 54
- Write a regex that finds a repeated word, like “the the”.
\b([A-Za-z]+)\s+\1\b: capture a word, then require the same text again after whitespace.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 54
- What is a non-capturing group, and when is it used?
(?: pattern ): groups for operator precedence without storing the match, e.g. to repeat a long sub-pattern 14 times but capture only the 15th occurrence.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 54
- How does ELIZA use regex substitutions?A cascade of substitutions on the uppercased input: first swap pronouns (MY → YOUR, I’M → YOU ARE), then match patterns and rewrite the whole response, e.g.
.* YOU ARE (DEPRESSED|SAD) .*→ “I AM SORRY TO HEAR YOU ARE \1”.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 55
- What are lookahead assertions?Zero-width tests on what comes next:
(?= pattern)succeeds if the pattern matches,(?! pattern)if it doesn’t, without advancing the match pointer. Negative lookahead is used to rule out special cases.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 55
- Write a regex capturing the first word of a line only if it doesn’t start with T or t.
^(?![tT])(\w+)\b- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 55
- What does the GPT-2 pretokenizer regex split “We’re 350 dogs! Um, lunch?” into?
We·’re·␣350·␣dogs·!·␣Um·,·␣lunch·?: contractions split off, words/numbers/punctuation runs separated, leading spaces attached.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, pp. 55–56
- What do
\p{L}and\p{N}match, and in which Python library?Any Unicode letter and any Unicode number (with\P{…}for the complements), in the externalregexlibrary, which is more powerful than the built-inre.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.6, p. 56
2.7 Simple Unix tools for word tokenization
- What does
tr -sc 'A-Za-z' '\n' < sh.txtdo?Tokenizes naively:-ccomplements the set (all non-letters), which are changed to newlines, and-ssqueezes runs into a single newline, giving one word per line.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.7, pp. 56–57
- Write a Unix pipeline that lists the most frequent words in a text file, case-insensitively.
tr -sc 'A-Za-z' '\n' < f.txt | tr A-Z a-z | sort | uniq -c | sort -n -r- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.7, p. 57
- What are the most frequent words in any corpus, Shakespeare included?Short function words: articles, pronouns, prepositions (the, and, i, to, of, a…).
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.7, p. 58
2.8 Rule-based tokenization
- When might we want rule-based word tokenization instead of BPE subwords?When tokens must be words: e.g. parsers needing grammatical words as input, linguistic studies with a predefined token definition, or social-science work on orthographic words.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.8, p. 58
- What does a good English rule-based tokenizer need to handle?Split off punctuation, but keep word-internal punctuation (m.p.h., Ph.D., AT&T), prices and dates ($45.55, 01/02/06), URLs, hashtags, emails, and numbers with commas (555,500.50). Number formats differ by language (555 500,50).
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.8, p. 58
- How can a rule-based tokenizer treat clitic contractions and multiword expressions?Expand contractions (what’re → what are, we’re → we are), and optionally keep multiword expressions like New York or rock ’n’ roll as one token using a dictionary, which ties tokenization to named entity recognition.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.8, p. 58
- Describe the Penn Treebank tokenization standard.Used for LDC treebanks: it separates clitics (doesn’t → does + n’t), keeps hyphenated words together, and separates all punctuation (and $ from amounts).
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.8, p. 59
- How are rule-based tokenizers made fast?Deterministic regular expressions compiled into efficient finite-state automata (e.g. NLTK’s
regexp_tokenize).- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.8, p. 59
- What ambiguity of the apostrophe must a careful tokenizer resolve?Genitive marker (the book’s cover), quotation mark (‘The other class’, she said), or clitic (they’re).
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.8, p. 59
- What is sentence segmentation, and which cues does it use in English?Splitting text into sentences. Question and exclamation marks are fairly unambiguous boundaries; the period is ambiguous.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.8, p. 59
- Why is the period hard for sentence segmentation, and how is it handled?It marks both sentence ends and abbreviations (Dr., Inc.), sometimes both at once. Segmenters decide whether a period belongs to a word, using rules or ML plus an abbreviation dictionary, often jointly with word tokenization.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.8, p. 60
- How does Stanford CoreNLP decide that a sentence ends?Deterministically from tokenization: a sentence ends when ., ! or ? is not already part of another token (abbreviation, number), optionally followed by closing quotes or brackets.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.8, p. 60
2.9 Minimum edit distance
- Define minimum edit distance.The minimum number of editing operations (insertion, deletion, substitution) needed to transform one string into another.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.9, p. 60
- What is an alignment between two strings?A correspondence between substrings of two sequences, often shown with an operation row (d, s, i) below the aligned strings.
Turning drive into brief: substitute d→b, delete v, insert f (Levenshtein distance 3).D R I V E * | | | | | | B R I * E F s d i- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.9, p. 60
- What is Levenshtein distance, and what is its alternative version?Each insertion, deletion and substitution costs 1 (identity substitution costs 0). In the alternative version substitutions are disallowed, equivalently cost 2 (a deletion plus an insertion).
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.9, p. 60
- Why can minimum edit distance be computed efficiently with dynamic programming?Many edit paths reach the same intermediate string, and the optimal path to the target must include the optimal path to every intermediate string on it. So we store the best solution for each subproblem in a table instead of searching all paths.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.9, p. 61
- What is dynamic programming?A class of table-driven algorithms (Bellman, 1957) that solve problems by combining solutions to subproblems. In NLP: minimum edit distance, Viterbi, CKY parsing.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.9, p. 61
- What is \(D[i,j]\) in the minimum edit distance algorithm, and what are its base cases?The edit distance between the first \(i\) characters of the source and the first \(j\) characters of the target. Base cases: \(D[i,0] = i\) deletions, \(D[0,j] = j\) insertions. The answer is \(D[n,m]\).
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.9, p. 62
- Give the recurrence for minimum edit distance.\(D[i,j] = \min\{D[i-1,j] + \text{del}(x_i),\; D[i,j-1] + \text{ins}(y_j),\; D[i-1,j-1] + \text{sub}(x_i, y_j)\}\), with \(\text{sub}(x,x) = 0\).
Each cell takes the cheapest of three neighbors plus an edit cost (rows = source). - Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.9, p. 62
- How do you get an alignment, not just a distance, out of the edit distance algorithm?Store backpointers in each cell to the neighbor(s) the minimum came from, then backtrace from \(D[n,m]\) to \(D[0,0]\). Each complete path is a minimum-cost alignment: a horizontal step is an insertion, a vertical step a deletion, a diagonal step a match or substitution.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.9, p. 62
- What are applications of minimum-edit-distance alignment?Computing word error rate in speech recognition, matching sentences in a parallel corpus for MT, and spelling correction.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.9, p. 63
- Why might edit operation costs not be uniform in spelling correction?Some errors are more likely, e.g. substitutions between letters that are adjacent on the keyboard, so the algorithm allows letter-specific weights.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.9, p. 64
- How does the Viterbi algorithm relate to minimum edit distance?It is a probabilistic extension: instead of the minimum-cost alignment of two strings it computes the maximum-probability alignment.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, §2.9, p. 64
Historical notes
- Where does BPE come from, and how did it enter NLP?It was a text compression method (Gage, 1994), applied to subword tokenization for neural MT by Sennrich et al. (2016), then adopted as the default by OpenAI’s GPT-2 and included in SentencePiece.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, Historical notes, p. 65
- Who first defined regular expressions, and how did grep get its name?Kleene (1951, 1956), along with finite automata, based on the McCulloch–Pitts neuron. Ken Thompson built regexes into editors; his ed command
g/regular expression/p(Global Regular Expression Print) became Unix grep.- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, Historical notes, p. 65
- Why did Bellman call his method “dynamic programming”?To hide that it was mathematical research from a Secretary of Defense who hated the word “research”: “dynamic” conveys multi-stage and is impossible to use pejoratively.
- Jurafsky & Martin, Speech and Language Processing, 3rd ed. draft, ch. 2, Historical notes, p. 65
Source
- Daniel Jurafsky and James H. Martin. Speech and Language Processing. 3rd edition (draft). https://web.stanford.edu/~jurafsky/slp3/