Week 01 · Text, Unicode, and tokenization
Compare code points, bytes, and tokens before counting text.
Compare code points, bytes, and tokens before counting text.
Work through the problem
A Unicode code point is an integer identifier. UTF-8 encodes each code point in one to four bytes. A visible character can contain several code points: é can be U+00E9 or e followed by a combining acute accent. Normalization can bring canonically equivalent strings to a common form.
The composed spelling of café uses four code points and five UTF-8 bytes. Its decomposed spelling uses five code points and six bytes. A tokenizer adds another convention: whitespace splitting, character splitting, or a learned subword vocabulary. These counts answer different questions.
Run the Python lab
import unicodedata
import re
text = "cafe\u0301"
for sample in [text,unicodedata.normalize("NFC",text),"猫","cache_hit"]:
print(repr(sample),len(sample),len(sample.encode("utf-8")),re.findall(r"\w+|[^\w\s]",sample))
assert len(text)==5 and len(unicodedata.normalize("NFC",text).encode())==5
Output from the lab
'café' 5 6 ['cafe', '́']
'café' 4 5 ['café']
'猫' 1 3 ['猫']
'cache_hit' 9 9 ['cache_hit']
Practice
- Why might you preserve the original bytes for identifiers?
Check your reasoning
- Normalization can alter which spellings compare equal. Decide and document whether identifiers follow normalized or byte-level equality.
Further reading · Jurafsky and Martin · Speech and Language Processing