從字元到位元組:碼位與 UTF-8
Agent 輔助工程檢查
前置要求
完成第 36 天。如受阻,使用第 35 天的回退連結複習機率與 Python。
學習目標
區分可見字元、其 Unicode 碼位與其 UTF-8 位元組序列;先預測位元組數再測量;針對空字串、ASCII、帶重音字元、中日韓字元與 emoji 記錄預測與觀測的對照。
操作指引
字元是讀者看到的形體;碼位是其 Unicode 編號(記作 U+XXXX);編碼把碼位轉換成位元組序列。必做工作:先預測,再執行 python3 -c "s='貓aé😀'; print(len(s), [hex(ord(c)) for c in s], list(s.encode('utf-8')))",逐項對照預測。選做工作:把同一字串用 UTF-16 編碼並比較位元組數。
自主實作與記錄
預測 s='貓aé😀' 與空字串 '' 的 len(s)、碼位序列與 UTF-8 位元組列表;隨後在 Python 中驗證,並解釋為什麼位元組數與碼位數不同。
UTF-8 中 ASCII 佔 1 位元組、多數帶重音拉丁字元佔 2 位元組、中日韓字元佔 3 位元組、多數 emoji 佔 4 位元組。ord() 回傳碼位,.encode('utf-8') 回傳位元組。
s='貓aé😀' 有 4 個碼位——U+732B(貓)、U+0061(a)、U+00E9(é)、U+1F600(😀)——但 UTF-8 位元組有 10 個:貓→[231,140,171],a→[97],é→[195,169],😀→[240,159,152,128]。空字串有 0 個碼位、0 個位元組。UTF-8 長度取決於碼位所在範圍,因此字元數與位元組數一般不相等。
對包括空字串在內的全體探測字串,你的書面預測與 ord()、encode() 的觀測輸出一致,並能說明碼位範圍到位元組數的對應規則。
權威來源資源與權利證明
Python Unicode HOWTO
對應章節 / 時間戳: Sections: Definitions of Character, Code Point, and Encodings (UTF-8)
驗證版本與日期: Python 3.12 documentation (Verified: 2026-10-30)
Normative reference for Python 3 code points, encodings, and variable-length UTF-8 byte behavior used in every tokenization step.
Basic Python strings and byte literals
The lesson defines every required Unicode concept locally and all commands run offline.
對比候選資源與選型分析 (2)
Exhaustive normative standard but far too deep for a first contact; the Python HOWTO teaches the same code point/encoding distinction in executable form.
Strong motivation and history but pre-Python-3 and not runnable; retained as optional background reading only.
minbpe: Minimal Byte-Pair Encoding tokenizer (Let's build the GPT Tokenizer)
對應章節 / 時間戳: README exercise flow and minbpe/base.py; lecture segment on Unicode code points vs raw bytes
驗證版本與日期: commit 1acefe9 (Verified: 2026-10-30)
Standard teaching reference connecting Unicode code points, UTF-8 bytes, and subword token ids for GPT-style tokenizers.
Basic Python and strings
The lesson re-implements the same algorithms locally in pure Python with verified outputs.
對比候選資源與選型分析 (3)
Production BPE with Rust core and regex pre-tokenization; selected as the production contrast source rather than the primary teaching implementation.
High-quality BPE coverage but frames tokenization through library APIs; minbpe exposes the raw merge loop for hand tracing.
Industrial tokenizer trainer supporting BPE and unigram models; C++ core hides the teaching mechanics.