Code-Switching and Mixed-Language Text › Mixed Scripts and Unicode Traps

Michael BrenndoerferNovember 26, 20266 min read
Language AI HandbookAll chapters
Part 26 of 67Multilingual Language Models and Cross-Lingual Transfer
Chapter 188Code-Switching and Mixed-Language Text › Mixed Scripts and Unicode Traps
Reading section 5 of 13 · Mixed Scripts and Unicode Traps · 6 minSection 5 of 13 · 6 min

Section 5 of 13 · 6 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Before you can classify a language, you have to see the text correctly. In mixed-language text this is harder than it sounds, and the failure modes are silent. A string that looks right on screen can be wrong in ways that only appear when you compare byte sequences, and the wrongness can survive every stage of a pipeline until it shows up as a quality problem that nobody can trace back to its source.

As we covered in Character Encoding and Text Normalization, different code-point sequences can be canonically equivalent. Applying the same normalization form gives them a common representation. Unicode normalization treats equivalence separately from visual resemblance.

Script composition per token

For each whitespace-delimited token, inspect the Unicode Script property of its letters. Match a small, named set of scripts with regex and record letters outside that set separately. Marks and punctuation are excluded from this particular diagnostic. Unicode Standard Annex #24 specifies the Script and Script_Extensions properties.

PythonIn [15]
CollapseExpand
scripts_to_track = (
    "Latin",
    "Han",
    "Arabic",
    "Cyrillic",
    "Greek",
    "Devanagari",
    "Hiragana",
    "Katakana",
)
script_patterns = {
    name: regex.compile(rf"\p{{Script={name}}}") for name in scripts_to_track
}


def token_scripts(token):
    scripts = set()
    for char in token:
        if char.isalpha():
            script = next(
                (
                    name
                    for name, pattern in script_patterns.items()
                    if pattern.fullmatch(char)
                ),
                "Untracked",
            )
            scripts.add(script)
    return sorted(scripts)


mixed_samples = [
    "我明天有 meeting at 3pm",
    "بس الملف لسه مش جاهز",
    "食べる",
    "Ελληνικά and English",
]
script_rows = [
    (text, [(token, token_scripts(token)) for token in text.split()])
    for text in mixed_samples
]
ConsoleOut [16]
CollapseExpand
我明天有 meeting at 3pm
    我明天有         ['Han']
    meeting      ['Latin']
    at           ['Latin']
    3pm          ['Latin']

بس الملف لسه مش جاهز
    بس           ['Arabic']
    الملف        ['Arabic']
    لسه          ['Arabic']
    مش           ['Arabic']
    جاهز         ['Arabic']

食べる
    食べる          ['Han', 'Hiragana']

Ελληνικά and English
    Ελληνικά     ['Greek']
    and          ['Latin']
    English      ['Latin']

The Mandarin–English and Greek–English examples have tokens in more than one script across the sentence. The Japanese word mixes Han and Hiragana inside a single token as part of its ordinary spelling. The Arabic example stays in one script. These are observations about writing systems. For example, a Romanized Hindi word and an English word can both be Latin-only.

A character filter designed for Latin text would lose information in these examples. A separate policy may be useful for identifier security. Unicode's UTS #39 describes how script mixing and visual confusability differ. This diagnostic counts scripts and does not attempt to infer intent or visual confusability.

PythonIn [17]
CollapseExpand
script_sample_labels = ["Han + Latin", "Arabic", "Japanese", "Greek + Latin"]
script_latin_only = []
script_non_latin = []
script_mixed_or_other = []
for text, per_token in script_rows:
    latin_only = non_latin = mixed_or_other = 0
    for tok, scripts in per_token:
        if scripts == ["Latin"]:
            latin_only += 1
        elif len(scripts) == 1 and scripts != ["Untracked"]:
            non_latin += 1
        else:
            mixed_or_other += 1
    script_latin_only.append(latin_only)
    script_non_latin.append(non_latin)
    script_mixed_or_other.append(mixed_or_other)

script_left_nonlatin = script_latin_only
script_left_mixed = [a + b for a, b in zip(script_latin_only, script_non_latin)]
VisualizationOut [18]
CollapseExpand
Stacked bars of Latin-only, non-Latin, and mixed-script token counts for four samples.
Script composition of whitespace-delimited tokens in four examples. The Japanese word contains Han and Hiragana in one token, while the Greek–English example mixes scripts across tokens.

Normalization hazards

Unicode normalization can support exact matching on canonically equivalent strings. The form you choose determines whether compatibility distinctions survive. See Unicode Standard Annex #15.

PythonIn [19]
CollapseExpand
norm_samples = [
    "Café",  # composed form
    "Cafe\u0301",  # decomposed form
    "CAFE",  # fullwidth Latin
    "カフェ",  # halfwidth Katakana
    "①",  # circled digit
]

norm_rows = []
for s in norm_samples:
    for form in ("NFC", "NFKC"):
        norm_rows.append((s, form, unicodedata.normalize(form, s)))
ConsoleOut [20]
CollapseExpand
NFC   'Café'                 -> 'Café'  (len 4 -> 4)
NFKC  'Café'                 -> 'Café'  (len 4 -> 4)
NFC   'Café'                -> 'Café'  (len 5 -> 4)
NFKC  'Café'                -> 'Café'  (len 5 -> 4)
NFC   'CAFE'                 -> 'CAFE'  (len 4 -> 4)
NFKC  'CAFE'                 -> 'CAFE'  (len 4 -> 4)
NFC   'カフェ'                  -> 'カフェ'  (len 3 -> 3)
NFKC  'カフェ'                  -> 'カフェ'  (len 3 -> 3)
NFC   '①'                    -> '①'  (len 1 -> 1)
NFKC  '①'                    -> '1'  (len 1 -> 1)
Logical offsets [3:7]: '\u0633\u0644\u0627\u0645'

The important observations:

  • NFC preserves these compatibility-only distinctions; NFKC folds them. Fullwidth Latin collapses to ASCII. Halfwidth Katakana collapses to fullwidth. Circled numerals become plain digits. If your corpus distinguishes Japanese halfwidth and fullwidth forms for any downstream reason, NFKC erases that distinction permanently.
  • Decomposed versus composed forms affect deduplication. A crawler that hashes raw bytes will see Café and Cafe\u0301 as different strings. If two otherwise identical documents differ in this sequence, a raw-byte deduplication pass will keep both.
  • Character filters can remove required marks. As a separate check, evaluate ''.join(ch for ch in 'कि' if ch.isalnum()). It returns क and drops the vowel sign ि. Keep a fixture for each relevant script before using a character whitelist.

Decode the input using its known encoding. Record the normalization form and apply it consistently. The two spellings of Café in the cell give the same NFC string, so the normalized value alone cannot tell you which sequence was supplied. Keep the raw text when you may need the original code-point sequence. Derive any script-specific whitelist from the corpus.

Bidirectional text

Ordinary Arabic-script and Hebrew-script letters display right to left. The Unicode Bidirectional Algorithm determines how mixed-direction text is displayed. The cell above checks that logical offsets [3:7] select the four Arabic letters in the test string. Test the visual order in the annotation tool separately.

Use logical text offsets to associate tokens with annotations. Verify that your interface displays each selected span correctly, including mixed-direction reference and hypothesis fields. Test isolation and index mapping together in the annotation UI.

Render a known mixed-direction sentence in the annotation tool and ask a bilingual reader to confirm its order. Select a span and check the stored offsets against the original logical string.

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!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy