Course contents 02 / 28

02 / 28 · Text Foundations

Text as data

Bytes, Unicode normalization, token offsets, and task-dependent information loss in an independently specified text-processing example.

On this page 6

An equipment label arrives as réglage L7. A second system sends what looks like the same label, but an exact string comparison fails. Before deciding that the messages describe different equipment, we need to inspect the representation. A visible letter, a Unicode code point, and a stored byte are different units.

What a string is#

A byte contains eight bits. A file or network message carries bytes; an encoding determines how those bytes represent text. UTF-8 uses variable-length byte sequences for Unicode code points. ASCII-range code points use one byte, while other code points can require more. Decoding the correct bytes with the wrong encoding can produce an error or unrelated characters.

A Python str is a sequence of Unicode code points. Its length counts those code points, rather than UTF-8 bytes or the symbols a reader perceives. In our composed label réglage L7, the accented é is one code point. The complete label contains ten code points and eleven UTF-8 bytes. In re\u0301glage L7, the accent is a separate combining code point after e: the label contains eleven code points and twelve bytes. The two strings can look the same while containing different sequences.

The Unicode standard distinguishes canonical equivalence from compatibility equivalence. Canonical normalization handles alternative encodings of the same abstract text. NFC decomposes canonically and then composes where the standard allows; NFD leaves the canonical decomposition. Applying NFC to both forms of our label gives the same string. Reapplying NFC does not keep changing it: normalization is idempotent. These definitions come from Unicode Standard Annex 15.

NFKC and NFKD also apply compatibility mappings. Those can collapse presentation distinctions that a task might need. In our identifier L7, the fullwidth letter becomes ordinary L under NFKC. That may be desirable for searching a typed inventory code. For a task transcribing the original typography, the distinction is part of the answer and should remain available.

Normalization is not spelling correction, translation, or a defense against every visually confusable identifier. It also does not determine what a person sees as one character. Combining sequences and some emoji sequences can contain several code points. A user interface may need grapheme-cluster boundaries; slicing a Python string by arbitrary code-point offsets is not a general user-perceived-character operation.

Preserve the original text alongside any normalized view when later operations need evidence, highlighting, or exact output. A transformation that loses information cannot reconstruct it from the transformed string alone. Keep the encoding and Unicode database version in the processing configuration. The saved calculations here use Python 3.9.7 with Unicode database 13.0.0; the reference standard defines the concepts independently of that runtime snapshot.

Segmentation: cutting the string into units#

After decoding, we choose units. Splitting on whitespace is an understandable baseline. For lamp L7: not ready!, it leaves L7: and ready! attached to punctuation. A rule that separates punctuation produces a different sequence. Neither is universally right: a colon can be formatting, part of a code, or a meaningful symbol in a language.

For this small example we choose an explicit regular-expression rule: a token is either a run matched by \w+, or one non-whitespace character outside \w. This is a Python regular-expression convention, not a linguistic definition of a word. In particular, underscores and digits are included in \w; combining marks and scripts without spaces require attention. We do not present the rule as a multilingual tokenizer.

Apply NFKC and case folding to the invented message lamp L7: not ready!. The normalized text becomes lamp l7: not ready!. With half-open code-point intervals, its tokens are:

TokenStartEnd
lamp04
l768
:89
not1013
ready1419
!1920

The two spaces explain why the second token starts at six. A half-open interval includes its start and excludes its end, so slicing the normalized string at each recorded interval returns the listed token. This is an invariant we can verify for every row.

Those offsets address the normalized string. They are not automatically offsets into the original bytes, or even into the original code-point sequence when normalization changes its length. An extraction application that highlights original input needs an explicit alignment map. Reusing transformed offsets without such a map can highlight the wrong phrase even when the extracted label is correct.

Sentence boundaries introduce a similar contract. Punctuation can indicate an abbreviation, a decimal, or the end of a sentence. A later model may operate on a whole message rather than sentences. Segment only to the extent required by the task, and measure the errors the segmentation creates.

Cleaning: trading information for a smaller vocabulary#

Suppose a dictionary is fitted on five invented labels: Lamp, lamp, Lamp, lamp!, and lamps. There are five distinct raw strings. NFKC reduces them to four because the fullwidth initial letter becomes L. Case folding reduces the count to three. Removing punctuation reduces it to two: lamp and lamps.

The vocabulary gets smaller because transformations identify previously different strings. That can help a model share observations. It can also merge inputs with different targets. If a preprocessing function gg maps two messages to the same representation, g(x1)=g(x2)g(x_1)=g(x_2), any deterministic classifier operating only on that representation must assign the same output to both. More training cannot recover the distinction once it has been discarded.

Case folding is designed for caseless comparison and can be more extensive than lowercasing. It may be appropriate for a case-insensitive search key, while exact case can matter for item codes or entity recognition. Specify which field is being transformed; a message and an identifier embedded within it need not follow the same rules.

Stopword removal deletes selected frequent tokens. Frequency by itself does not show that a token is irrelevant. In our message, deleting not turns the retained words into lamp l7 ready. That can reverse the practical meaning. A list useful for one retrieval baseline is not automatically suitable for fault classification or response generation.

Stemming applies rules that reduce related forms to a common stem; the result need not be a dictionary word. Lemmatization seeks a dictionary form, often using morphological or contextual information. These choices may pool evidence across inflections, but they can also erase distinctions needed for agreement, tense, or exact quotation. We do not run an English stemmer on Russian text and assume that the resulting strings are useful features.

The choice must also agree with the downstream model. A pretrained tokenizer expects its own normalization and segmentation rules. Applying extra punctuation deletion before that tokenizer changes the input distribution. For code, URLs, or structured identifiers, the deleted characters may be essential.

Worked example#

We can describe the preprocessing chain as a sequence of testable contracts. The input is a Unicode string. NFKC constructs a compatibility-normalized view. Case folding constructs a comparison view. The regular expression produces tokens and code-point spans in that view. The original string remains available separately.

For lamp L7: not ready!, the output has six tokens. All six spans recover their token exactly. If a search index keeps only words, it may discard : and ! while retaining not. If an exact-message archive is being built, it keeps the full original string and uses the normalized view only as an additional index key.

The alternative pipeline that deletes not, :, and ! produces three retained words. Fewer tokens do not establish a better representation. The shorter output has lost the particular distinction the fault classifier needs. We can diagnose that failure before training a model because the transformation itself creates the collision.

For the five label variants, the sequence of distinct-type counts is 5→4→3→25\to4\to3\to2. These are exact counts for our supplied inputs. They are not measured compression ratios for a real corpus, and they do not predict the effect on classification accuracy. A production decision needs an evaluation set containing the distinctions we care about.

Why preprocessing depends on the task#

For approximate search, a normalized lookup key can help a query match a differently entered label. Store the retrieved original as the display value. For extraction, preserve enough alignment to return spans in the required coordinate system. For generation, consider whether the model must reproduce typography, identifiers, or whitespace exactly.

There is a second boundary between fixed transformations and fitted transformations. A chosen NFC normalization does not learn frequencies from the evaluation set. A vocabulary, document-frequency table, or learned tokenizer does. Fit those components on the permitted training data and freeze them before evaluating. Otherwise the evaluation text influences the representation whose generalization is being measured.

Version the whole chain, including the order of operations. Normalization followed by tokenization may differ from tokenization followed by per-token normalization, particularly when a transformation changes boundaries. A saved vocabulary without its normalization rules is an incomplete representation contract.

For an established model, use the tokenizer and configuration associated with that exact model revision. A token ID is an index into the model’s learned parameters. Swapping two IDs while preserving all token strings changes which learned vector each input selects. A tokenizer update therefore needs compatibility checks rather than merely a comparison of vocabulary sizes.

Limitations#

Our regular expression handles the deliberately simple labels used here; it is not a complete language segmentation method. Unicode normalization does not resolve semantic ambiguity or repair mislabeled data. A smaller vocabulary does not establish an improvement, and exact normalization equality does not imply that two messages have the same intent.

The raw input may also contain sensitive information. Retaining it for alignment does not imply retaining it indefinitely or making it public. A real collection needs a justified retention boundary, access rules, and a documented source. Our fixture contains only newly invented text.

What you should remember#

Choose the coordinate system: bytes, code points, or user-perceived characters. Keep normalization and linguistic interpretation separate. Preserve raw text or alignment when the task needs exact spans. Treat cleaning as an information-loss decision, and keep fitted vocabulary statistics out of the held-out data.

Reproducible example#

  • The text_data case in the standalone Python script uses only the standard library. It verifies NFC equality and idempotence, all six normalized offsets, the destructive removal of not, and the four type counts. Saved output records Python’s Unicode database version. No real messages or external corpus are included.

Next#

A word dictionary still gives different entries to many related forms and cannot cover every new identifier. Tokenization builds smaller reusable units and makes the trade-off between vocabulary size and sequence length explicit.

References#

  • Unicode Consortium, editor Ken Whistler. Unicode Standard Annex 15: Unicode Normalization Forms, revision 58, Unicode 18.0.0, 2026. Sections 1.1–1.3 and 7: equivalence, normalization forms, and idempotence. Definitions are referenced; standard figures and example tables are not reproduced.
  • Python Software Foundation. Unicode HOWTO and unicodedata, Python 3.9 documentation. String/code-point/encoding distinction and runtime normalization API.
  • Hugging Face course contributors. Normalization and pre-tokenization, pinned revision 8b893f0. Normalization, segmentation, and offset contracts; no external figures, model files, or source examples are used here.