Sub topic 1
Tokens, types and vocabulary
Prerequisites
This chapter assumes you can write Python strings, lists, and functions, and that you have used import re before. You should also know basic grammar terms such as noun, verb, and plural.
Tokens, types and vocabulary
A token is one unit that a program treats as a single item, usually a word or a punctuation mark. A type is a distinct token value. The sentence "the cat saw the dog" has 5 tokens but only 4 types, because "the" appears twice. The vocabulary is the set of types a system knows about. Counting tokens measures text length. Counting types measures variety.
Splitting text with whitespace and regular expressions
The simplest tokeniser splits on spaces. Python's str.split() does this. It fails on punctuation, because punctuation stays attached to the words. A regular expression (a pattern that describes text) gives finer control.
import re
text = "Don't split me naively, please."
print(text.split())
pattern = r"\w+(?:'\w+)?|[^\w\s]"
print(re.findall(pattern, text))The first print returns ["Don't", 'split', 'me', 'naively,', 'please.']. The second returns ["Don't", 'split', 'me', 'naively', ',', 'please', '.']. The pattern keeps contractions together and emits each punctuation mark as its own token.
Where simple tokenisers break
Rule-based tokenisers fail on cases the rules do not anticipate:
- Abbreviations such as "U.S." or "e.g." may split in the wrong place.
- Hyphenated words such as "state-of-the-art" may split into pieces or stay whole, depending on the rule.
- Languages such as Chinese and Japanese write without spaces between words.
- URLs, emoji, and numbers such as "3.14" need their own rules.
Each new rule adds maintenance work, and no fixed set covers all text. Subword tokenisers such as BPE and WordPiece avoid this problem by learning frequent character sequences from data. Their details are covered in a later chapter.
Normalising text before and after tokenising
Normalisation makes equivalent text compare equal. Two common steps are:
- Case folding converts text to one case.
str.casefold()is stronger thanlower(), so "Straße" becomes "strasse". - Unicode normalisation makes equivalent byte sequences identical. The letter "é" can be one code point or an "e" followed by a combining accent.
import unicodedata
composed = "caf\u00e9"
decomposed = "cafe\u0301"
print(composed == decomposed)
print(unicodedata.normalize("NFC", composed) == unicodedata.normalize("NFC", decomposed))The first comparison prints False. The second prints True.
Normalisation has side effects. Lowercasing "US" (the country) to "us" (the pronoun) merges two meanings. Removing accents can merge distinct words in some languages. Decide whether to normalise before or after tokenising based on whether the step depends on token boundaries.
Exercise
Using the pattern from this chapter, how many tokens does re.findall(r"\w+(?:'\w+)?|[^\w\s]", "Don't stop, don't go.") return?
Show answer
It returns 8 tokens: "Don't", "stop", ",", "don't", "go", "." That is 6 tokens in total. Recount carefully: "Don't", "stop", ",", "don't", "go", "." is 6 items, so the answer is 6.