Language Diversity, Typology, and Scripts › Code Implementation
Language AI HandbookAll chapters Setup
The chapter uses the Language AI Handbook Python environment. The examples use in-memory strings, pandas tables, and Matplotlib figures. The tokenizer is trained from scratch with tokenizers 0.22.2, and regex 2026.2.28 supplies default extended grapheme cluster matching.
Counting Characters Across Scripts
The ranges below are convenient slices of Unicode associated with selected scripts. Count assigned codepoints in each range, excluding controls, format characters, surrogates, and private-use codepoints. This estimates the size of the selected ranges, which can include punctuation and omit blocks associated with the same script. Unicode's Script property is a separate classification.
PythonIn [3]Expand
script_ranges = {
"Latin": [(0x0041, 0x005A), (0x0061, 0x007A), (0x00C0, 0x024F)],
"Greek": [(0x0370, 0x03FF), (0x1F00, 0x1FFF)],
"Cyrillic": [(0x0400, 0x04FF), (0x0500, 0x052F)],
"Armenian": [(0x0530, 0x058F)],
"Hebrew": [(0x0590, 0x05FF)],
"Arabic": [(0x0600, 0x06FF), (0x0750, 0x077F)],
"Devanagari": [(0x0900, 0x097F)],
"Bengali": [(0x0980, 0x09FF)],
"Thai": [(0x0E00, 0x0E7F)],
"Tibetan": [(0x0F00, 0x0FFF)],
"Georgian": [(0x10A0, 0x10FF)],
"Hangul": [(0x1100, 0x11FF), (0xAC00, 0xD7AF)],
"Hiragana": [(0x3040, 0x309F)],
"Katakana": [(0x30A0, 0x30FF)],
"Han": [(0x4E00, 0x9FFF)],
"Ethiopic": [(0x1200, 0x137F)],
"Cherokee": [(0x13A0, 0x13FF)],
}
def count_assigned(ranges):
total = 0
for lo, hi in ranges:
for cp in range(lo, hi + 1):
if unicodedata.category(chr(cp)) not in (
"Cn",
"Cs",
"Co",
"Cc",
"Cf",
):
total += 1
return total
script_sizes = pd.DataFrame(
{
"Script": list(script_ranges.keys()),
"Assigned codepoints": [
count_assigned(r) for r in script_ranges.values()
],
}
)
script_sizes = script_sizes.sort_values(
"Assigned codepoints", ascending=False
).reset_index(drop=True)ConsoleOut [4]Expand
Script Assigned codepoints
Han 20992
Hangul 11428
Latin 452
Greek 368
Ethiopic 358
Cyrillic 304
Arabic 296
Tibetan 211
Devanagari 128
Bengali 96
Katakana 96
Hiragana 93
Cherokee 92
Armenian 91
Georgian 88
Hebrew 88
Thai 87
Total assigned across these script ranges: 35268The selected basic Han range and Hangul syllable block contain far more assigned codepoints than the Latin ranges shown. Hangul's precomposed syllables and its conjoining letters have separate encodings. The table counts assigned values in the stated ranges. Measure the frequency of actual text and tokenizer fallback separately.
VisualizationOut [5]Expand

Multilingual String Fixtures
Start with the English fixture “The quick brown fox jumps over the lazy dog.” The dataset uses short, manually labeled strings for the notebook exercise. Use these strings to compare encodings. For a translation benchmark, collect human-validated translations and document their varieties.
PythonIn [6]Expand
samples = [
("English", "Latin", "The quick brown fox jumps over the lazy dog."),
(
"German",
"Latin",
"Der schnelle braune Fuchs springt über den faulen Hund.",
),
(
"Spanish",
"Latin",
"El rápido zorro marrón salta sobre el perro perezoso.",
),
(
"Turkish",
"Latin",
"Hızlı kahverengi tilki tembel köpeğin üzerinden atlar.",
),
("Finnish", "Latin", "Nopea ruskea kettu hyppää laiskan koiran yli."),
(
"Swahili",
"Latin",
"Mbweha wa haraka wa rangi ya kahawia anaruka juu ya mbwa mwivu.",
),
(
"Vietnamese",
"Latin",
"Con cáo nâu nhanh nhẹn nhảy qua con chó lười biếng.",
),
(
"Russian",
"Cyrillic",
"Быстрая коричневая лиса прыгает через ленивую собаку.",
),
(
"Greek",
"Greek",
"Η γρήγορη καφέ αλεπού πηδάει πάνω από τον τεμπέλη σκύλο.",
),
("Arabic", "Arabic", "الثعلب البني السريع يقفز فوق الكلب الكسول."),
("Hebrew", "Hebrew", "השועל החום המהיר קופץ מעל הכלב העצלן."),
("Hindi", "Devanagari", "तेज़ भूरी लोमड़ी आलसी कुत्ते के ऊपर कूदती है।"),
("Bengali", "Bengali", "দ্রুত বাদামী শিয়াল অলস কুকুরের উপর দিয়ে লাফিয়ে যায়।"),
("Thai", "Thai", "สุนัขจิ้งจอกสีน้ำตาลกระโดดข้ามสุนัขขี้เกียจ"),
("Tibetan", "Tibetan", "མགྱོགས་པོའི་ཁྱི་ནག་ཅན་གྱི་ལེབ་ལ་མཆོང་།"),
("Amharic", "Ethiopic", "ፈጣኑ ቡናማ ቀበሮ ሰነፉን ውሻ ዘሎ አለፈ።"),
("Mandarin", "Han", "敏捷的棕色狐狸跳过了懒狗。"),
("Japanese", "Han/Kana", "素早い茶色のキツネが怠け者の犬を飛び越えた。"),
("Korean", "Hangul", "빠른 갈색 여우가 게으른 개를 뛰어넘는다."),
]
assert all(sentence.strip() for _, _, sentence in samples)The fixture contains 19 labeled strings. Its labels identify the comparison rows. The Japanese row includes the Han character 茶 and kana such as の. This notebook measures the strings supplied in the table.
Measuring Tokenizer Fertility
Train a byte-level BPE tokenizer with a budget of 360 vocabulary entries, including all 256 byte symbols. The small English corpus is separate from the evaluation strings. Use no normalization and let the tokenizer learn merges only from the training strings. Comparing with the unmerged UTF-8 byte count shows how much segmentation each example gains from those merges.
Fertility here is tokens divided by Python's len(sentence), which counts codepoints, including punctuation and whitespace. The second measure divides the same numerator by whitespace-separated spans for samples where spaces usually separate words. Those spans are an approximation of words.
PythonIn [7]Expand
training_sentences = [
"A brown dog waited near the window and watched the street.",
"A red fox ran quickly along the bank of the river.",
"The children jumped over the puddles on their way home.",
"The farmer called the dogs back before the evening rain.",
"A dog can hear the sound of a small animal in the grass.",
"The lazy cat slept while the other animals explored the garden.",
"Brown leaves fell as the quick wind blew over the fields.",
"Wild animals need room to move between the fields and the woods.",
"The students collected examples and compared their results.",
"A short sentence can contain a few common words.",
]
tokenizer = Tokenizer(models.BPE())
tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
tokenizer.decoder = decoders.ByteLevel()
trainer = trainers.BpeTrainer(
vocab_size=360,
initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),
show_progress=False,
)
tokenizer.train_from_iterator(training_sentences, trainer=trainer)
non_space_word_boundaries = {"Mandarin", "Japanese", "Thai", "Tibetan"}
rows = []
for language, script, sentence in samples:
token_ids = tokenizer.encode(sentence).ids
assert tokenizer.decode(token_ids) == sentence
codepoints = len(sentence)
byte_count = len(sentence.encode("utf-8"))
tokens = len(token_ids)
space_count = (
float("nan")
if language in non_space_word_boundaries
else len(sentence.split())
)
rows.append(
{
"Language": language,
"Script": script,
"Codepoints": codepoints,
"UTF-8 bytes": byte_count,
"Tokens": tokens,
"Tokens/codepoint": tokens / codepoints,
"Tokens/space-delimited span": tokens / space_count,
}
)
fertility = pd.DataFrame(rows).sort_values("Tokens/codepoint", ascending=False)
english_density = fertility.loc[
fertility["Language"] == "English", "Tokens/codepoint"
].item()ConsoleOut [8]Expand
Language Script Codepoints UTF-8 bytes Tokens Tokens/codepoint Tokens/space-delimited span
Japanese Han/Kana 22 66 66 3.000 N/A
Mandarin Han 13 39 39 3.000 N/A
Tibetan Tibetan 38 114 114 3.000 N/A
Thai Thai 43 129 129 3.000 N/A
Bengali Bengali 55 149 149 2.709 16.556
Hindi Devanagari 45 119 119 2.644 13.222
Amharic Ethiopic 27 69 69 2.556 9.857
Korean Hangul 23 57 57 2.478 9.500
Russian Cyrillic 53 99 99 1.868 14.143
Arabic Arabic 42 77 77 1.833 11.000
Greek Greek 56 102 102 1.821 10.200
Hebrew Hebrew 37 67 67 1.811 9.571
Vietnamese Latin 51 63 54 1.059 4.909
Finnish Latin 45 47 42 0.933 6.000
Turkish Latin 54 59 48 0.889 6.857
Spanish Latin 53 55 45 0.849 5.000
Swahili Latin 63 63 52 0.825 4.333
German Latin 55 56 42 0.764 4.667
English Latin 44 44 18 0.409 2.000The UTF-8 column gives a baseline because the example tokenizer is lossless. Where the token count matches the byte count, the tokenizer found no applicable merges. The next cell prints the token pieces for the English and Mandarin strings. Compare the pieces and counts for these two fixtures. A single string per label supports a fixture comparison.
PythonIn [9]Expand
for language, _, sentence in samples:
if language in {"English", "Mandarin"}:
print(f"{language}: {tokenizer.encode(sentence).tokens}")ConsoleOut [9]Expand
English: ['The', 'Ġquick', 'Ġb', 'rown', 'Ġf', 'o', 'x', 'Ġ', 'ju', 'mp', 's', 'Ġover', 'Ġthe', 'Ġ', 'laz', 'y', 'Ġdog', '.'] Mandarin: ['æ', 'ķ', 'ı', 'æ', 'į', '·', 'ç', 'ļ', 'Ħ', 'æ', '£', 'ķ', 'è', 'ī', '²', 'ç', 'ĭ', 'IJ', 'ç', 'ĭ', '¸', 'è', '·', '³', 'è', '¿', 'ĩ', 'ä', 'º', 'Ĩ', 'æ', 'ĩ', 'Ĵ', 'ç', 'ĭ', 'Ĺ', 'ã', 'Ģ', 'Ĥ']
Visualizing Tokenizer Fertility
The chart sorts these specific examples by token density. The dashed line shows the English example on the same scale. Because the density divides by codepoints, two examples can have the same density and different total token counts.
VisualizationOut [10]Expand

The English example falls below the examples that retain almost all of their original UTF-8 byte units. The difference is expected in this deliberately narrow training setting. With a larger, differently mixed corpus or another tokenization algorithm, the rankings and the size of the gaps can change.
Who Pays: Fertility vs. Speaker Count
Population and fertility answer different questions. To connect them for capacity planning, consider four alternative input examples and a hypothetical service with 0.1%, or one in a thousand, of speakers each submitting one request. The speaker counts below are scenario inputs shared by all four examples. The calculation multiplies the number of requests by the total tokens in each example.
PythonIn [11]Expand
speaker_counts = np.array([1, 10, 100, 1_000]) * 1_000_000
speakers_per_request = 1_000
request_counts = speaker_counts // speakers_per_request
budget_examples = ["English", "Hindi", "Mandarin", "Amharic"]
example_tokens = fertility.set_index("Language").loc[budget_examples, "Tokens"]
total_input_tokens = example_tokens.to_numpy()[:, None] * request_countsVisualizationOut [12]Expand

With equal participation and one request per participant, doubling the audience doubles projected volume. At a fixed audience size, the longer tokenized example yields the larger projection. For a real service, replace each one-sentence token count with a measured request-length distribution and estimate participation from the target audience.
Word Order Across Documented Languages
The WALS sample gives us a second quantitative exercise. Use 1,376 as the denominator for the retained Feature 81A table and include the category for languages without a dominant order.
PythonIn [13]Expand
wals_orders = pd.DataFrame(
{
"Order": ["SOV", "SVO", "VSO", "VOS", "OVS", "OSV", "No dominant"],
"Count": [564, 488, 95, 25, 11, 4, 189],
}
)
wals_orders["Share (%)"] = (
100 * wals_orders["Count"] / wals_orders["Count"].sum()
)ConsoleOut [14]Expand
Order Count Share (%)
SOV 564 40.988372
SVO 488 35.465116
VSO 95 6.904070
VOS 25 1.816860
OVS 11 0.799419
OSV 4 0.290698
No dominant 189 13.735465
SVO (English's order) share within the WALS 81A sample: 35.5%VisualizationOut [15]Expand

SOV and SVO account for about 76% of this sample. VOS, OVS, and OSV together account for just under 3%. The roughly 14% of languages without a dominant order include different patterns. In the WALS coding, some permit substantial flexibility, while others use different orders under different grammatical conditions. A dataset built only from fixed-order English examples would leave many of these constructions out.
Graphemes vs. Codepoints: The Devanagari and Arabic Problem
A Unicode codepoint, an extended grapheme cluster, and a learned token count different things. Here we use \X from regex to count default extended grapheme clusters under the package's Unicode segmentation rules. Then we compare the number of codepoints in NFC and NFD. Under Unicode Standard Annex #15, both are canonical forms. NFD decomposes canonically equivalent sequences. NFC uses canonical composition where possible.
PythonIn [16]Expand
grapheme_examples = [
("English", "café"),
("Hindi greeting", "नमस्ते"),
("Hindi conjunct", "क्ष"),
("Arabic", "مَرْحَبًا"),
("Vietnamese", "Tiếng Việt"),
("Korean", "한국어"),
]
rows = []
for name, sample in grapheme_examples:
nfc = unicodedata.normalize("NFC", sample)
nfd = unicodedata.normalize("NFD", sample)
nfc_clusters = regex.findall(r"\X", nfc)
nfd_clusters = regex.findall(r"\X", nfd)
assert len(nfc_clusters) == len(nfd_clusters)
rows.append(
{
"Example": name,
"Text": sample,
"NFC codepoints": len(nfc),
"NFD codepoints": len(nfd),
"Grapheme clusters": len(nfc_clusters),
}
)
norm_df = pd.DataFrame(rows)
positions = np.arange(len(norm_df))ConsoleOut [17]Expand
Example Text NFC codepoints NFD codepoints Grapheme clusters
English café 4 5 4
Hindi greeting नमस्ते 6 6 3
Hindi conjunct क्ष 3 3 1
Arabic مَرْحَبًا 9 9 5
Vietnamese Tiếng Việt 10 14 10
Korean 한국어 3 8 3In this Unicode segmentation, the three codepoints in क्ष form one default extended grapheme cluster. The Arabic example also has fewer clusters than codepoints because the combining marks attach to base letters. In Korean, the three precomposed syllables in "한국어" expand to eight conjoining jamo codepoints under NFD and still form three clusters. A learned tokenizer might split either representation differently. The NFC and NFD strings can compare unequal as raw sequences of codepoints. Normalizing both to the same form makes canonically equivalent strings compare equal.
VisualizationOut [18]Expand

Morpheme Counts in Five Examples
A morpheme count depends on the analysis assigned to each word. The examples below let us compare explicit segmentations, including the Inuktitut analysis cited above. They come from different grammatical constructions and are hand-selected for illustration. Counting the listed pieces makes the measurement reproducible.
PythonIn [19]Expand
morph_rows = [
("English", "unbelievably", "un-believ-able-ly"),
("Turkish", "evlerinizden", "ev-ler-iniz-den"),
("Finnish", "talossanikin", "talo-ssa-ni-kin"),
("Swahili", "unamwona", "u-na-mw-ona"),
(
"Inuktitut",
"titiraqtautsiarunnaqullugit",
"titiraq-tau-tsia-runna-qu-llu-git",
),
]
morph_df = pd.DataFrame(
morph_rows, columns=["Language", "Word", "Morpheme analysis"]
)
morph_df["Morpheme count"] = (
morph_df["Morpheme analysis"].str.split("-").str.len()
)
morph_df = morph_df.sort_values("Morpheme count")ConsoleOut [20]Expand
Language Word Morpheme analysis Morpheme count English unbelievably un-believ-able-ly 4 Turkish evlerinizden ev-ler-iniz-den 4 Finnish talossanikin talo-ssa-ni-kin 4 Swahili unamwona u-na-mw-ona 4 Inuktitut titiraqtautsiarunnaqullugit titiraq-tau-tsia-runna-qu-llu-git 7
In the English row, the written form is unbelievably and the table labels its analysis un-believ-able-ly. The chart counts the units in each stated analysis.
VisualizationOut [21]Expand

The chart uses the seven-piece partial analysis of the Inuktitut example. The full analysis in the same paper has eight pieces. The English gloss is a subordinate clause. The other four examples show that several words can have the same count while the pieces have very different grammatical functions. One word per language tells us how these five analyses compare. A language-level study would need representative corpora, word-boundary conventions, and consistent segmentation rules.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!