Turning files into indexable text takes four decisions: the character encoding, the file format's text extraction, the language, and the unit that counts as one document. Each can fail without an error. UTF-8 résumé read as Windows-1252 becomes résumé, indexed as rã and sumã; Latin-1 bytes read as UTF-8 give r and sum, or rsum. In Reuters-21578 the undecoded entity < occurs 8,694 times and puts the term lt in 56 percent of the 10,788 stories. A Cavnar–Trenkle n-gram identifier with 300-entry profiles for nine languages labels 20-character snippets correctly 85 percent of the time (median of 30 seeded runs) and 400-character ones 97 percent, failing mostly between close relatives such as Malay and Indonesian. Units too large cost precision; units too small cost recall.
In the architecture article, the thesis student's four Arctic documents arrived as clean English sentences, so parsing them took no work at all. A real collection does not arrive that way. It arrives as files: bytes on a disk, in some character encoding, inside some file format, written in some language, and grouped in units that nobody chose with search in mind. How do those bytes become text that an analyzer can split into words, and what should count as one document?
The answer has four parts, and together they make up the first stage of text processing, sometimes called document delineation: decoding the character encoding, identifying the file format and extracting its text, identifying the language, and choosing the unit that will count as one document (Manning, Raghavan, and Schütze, 2008, §2.1; language identification in §2.2.1).
Here is the route. First we follow one word, résumé, from its bytes to a broken index entry, to see why this stage needs explicit checks. Then we look at how encodings work, how UTF-8 packs a character into bytes, and the three ways decoding goes wrong. Next we turn to file formats and text extraction, with an extraction error that sits in Reuters-21578, the collection of 10,788 news stories that this topic uses for all its measurements. Then we work a classic language identifier by hand and measure where it fails. Finally we decide what counts as a document. Worked problems at the end encode, decode and mis-decode further strings by hand.
A word that vanishes without an error
The word résumé is six characters long. Stored as UTF-8, it occupies eight bytes, because each é needs two:
r é s u m é
114 195 169 115 117 109 195 169
Suppose a program reads those eight bytes but assumes they are in Windows-1252, the default encoding of many older Windows applications. It will decode each two-byte sequence as two separate characters and produce résumé. Nothing fails. The indexer receives a valid string, tokenizes it, and stores fragments such as rã and sumã. Every query for résumé or resume will now miss the document.
The damage is invisible in the output. It stays in the index until someone decodes the document again from its original bytes. That is why the first step of text processing needs explicit checks: turning bytes into characters, and deciding what those characters belong to. To see where checks can go, we first need to know how characters become bytes.
Characters and encodings
A computer stores text as numbers. A character encoding is the rule that maps between them.
ASCII, standardized in the 1960s, assigns the numbers 0 to 127 to unaccented Latin letters, digits, punctuation, and control characters. It fits in seven bits and covers English, but not é, ß, ж, or 中.
To cover other languages, many single-byte code pages used the remaining 128 values of an eight-bit byte for additional characters. ISO 8859-1 (Latin-1) and Windows-1252 cover Western European languages. Other code pages cover Cyrillic, Greek, and so on. A byte value such as 233 therefore means é in Latin-1 and something else entirely in a Cyrillic code page. The byte alone does not say which.
Unicode resolves this by giving every character in every writing system a single number, its code point. A code point is written as U+ followed by hexadecimal digits: é is U+00E9, € is U+20AC, 中 is U+4E2D. A character as a reader perceives it can also be a sequence of code points. For example, é can be stored either as U+00E9 or as e followed by U+0301, a combining acute accent. Normalization must later reconcile the two.
Unicode defines what the characters are. Several encoding forms then define how code points become bytes:
| Character | Code point | UTF-8 bytes | UTF-8 length (bytes) | UTF-16 length (bytes) |
|---|---|---|---|---|
| A | U+0041 | 41 |
1 | 2 |
| é | U+00E9 | C3 A9 |
2 | 2 |
| € | U+20AC | E2 82 AC |
3 | 2 |
| 中 | U+4E2D | E4 B8 AD |
3 | 2 |
| 😀 | U+1F600 | F0 9F 98 80 |
4 | 4 |
UTF-8 was designed by Ken Thompson and Rob Pike in 1992 (Pike and Thompson, 1993; Yergeau, 2003). It uses one to four bytes per character, and three properties of its design matter for text processing:
- Every ASCII file is already valid UTF-8, so existing English text needed no conversion.
- The first byte of each character announces how many bytes follow. The following bytes always have the form
10xxxxxx, which can never be mistaken for a first byte. A program can therefore find character boundaries starting from any point in a stream. - Byte sequences that are invalid UTF-8 are easy to detect. This makes UTF-8 one of the few encodings that can be partly recognized from the bytes alone.
UTF-8 has become the dominant encoding on the web and the usual internal representation in text processing systems. In November 2026 the W3Techs survey counted it on 99 percent of the websites whose encoding it could determine (W3Techs, 2026). UTF-16, used internally by Windows, Java, and JavaScript, uses two bytes for most characters and four for the rest.
Example (four bytes in UTF-16). The emoji 😀, U+1F600, takes the two 16-bit units D83D and DE00 in UTF-16. A code point up to U+FFFF is stored as one 16-bit unit holding its own value. A code point above U+FFFF does not fit in 16 bits and is stored as a surrogate pair (The Unicode Standard, section 3.9). Subtract hexadecimal 10000 from the code point, which leaves a number of at most 20 bits: $\text{1F600} - \text{10000} = \text{0F600}$, in binary 0000111101 1000000000. The high ten bits, 0000111101 (hexadecimal 03D), are added to D800 to give the first unit, D83D. The low ten bits, 1000000000 (hexadecimal 200), are added to DC00 to give the second, DE00. The ranges D800 to DBFF and DC00 to DFFF are reserved for these units and are assigned to no character, so a decoder can tell a half of a pair from a whole character. A program that counts 16-bit units therefore counts 😀 as two, which is why the same string can have different lengths in different programming languages.
How UTF-8 packs a code point
All three properties follow from one bit layout, specified in RFC 3629 (Yergeau, 2003, §3). Here is the idea in one sentence: the code point's bits are poured into fixed slots, and the fixed bits around the slots say how many bytes belong together.
The formal version. A code point is written in binary, and its bits fill the x positions of one of four patterns, chosen by how many bits the code point needs:
| Code points | Bits needed | Byte pattern |
|---|---|---|
| U+0000 to U+007F | up to 7 | 0xxxxxxx |
| U+0080 to U+07FF | up to 11 | 110xxxxx 10xxxxxx |
| U+0800 to U+FFFF | up to 16 | 1110xxxx 10xxxxxx 10xxxxxx |
| U+10000 to U+10FFFF | up to 21 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
Take é, U+00E9. In binary, hexadecimal E9 is 11101001. That is eight bits, too many for the one-byte pattern, so the two-byte pattern is used. Its eleven payload positions take the code point padded on the left to eleven bits, 00011101001. The first five bits, 00011, fill the first byte, and the remaining six, 101001, fill the second:
| Prefix | Payload | Byte | Hex | |
|---|---|---|---|---|
| First byte | 110 |
00011 |
11000011 |
C3 |
| Second byte | 10 |
101001 |
10101001 |
A9 |
These are the bytes 195 and 169 of résumé at the top of this article.
The euro sign U+20AC needs fourteen bits, more than the two-byte pattern's eleven, so it takes the three-byte pattern. Padded on the left to that pattern's sixteen payload positions, it is 0010 0000 1010 1100. Split four, six, and six, that gives 0010, 000010, and 101100. The bytes are 1110 0010 (E2), 10 000010 (82), and 10 101100 (AC), as in the table above.
Reading in the other direction, a decoder that sees a byte beginning 1110 knows that exactly two continuation bytes beginning 10 must follow. That is what makes damage detectable.
Example (a Chinese character). The Chinese character 中, U+4E2D, takes three bytes in UTF-8, with the pattern 1110xxxx 10xxxxxx 10xxxxxx. Hexadecimal 4E2D is 0100 1110 0010 1101, which needs fifteen bits once the leading zero is dropped. That is more than the two-byte pattern's eleven and no more than the three-byte pattern's sixteen. Split four, six, and six, the sixteen bits are 0100, 111000, and 101101, so the bytes are 1110 0100 (E4), 10 111000 (B8), and 10 101101 (AD), as the encoding table shows.
Stored order and displayed order
One more property of the character sequence matters to an indexer. Arabic and Hebrew are written from right to left, with numbers and quoted foreign words running from left to right inside the same line. In Unicode the characters of such text are stored in the order in which they are read and spoken, and the reversals seen on the page are made by the software that displays the text. Manning, Raghavan, and Schütze (2008, §2.1.1) make this point and add that it may not hold for documents in older encodings. An indexer therefore works on the stored order, in which the words of a phrase follow one another as a reader meets them, and not on the order of the glyphs on the screen.
Detecting the encoding
The decoder must know the encoding before it can produce characters, and documents do not always say. The evidence, roughly in order of reliability, is the following, although each format defines its own precedence rules:
- Byte order marks: a few bytes at the start of some files that identify UTF-8, UTF-16, or UTF-32. Browsers following the HTML standard let a byte order mark override any declaration.
- Declared encodings: the
charsetparameter of an HTTPContent-Typeheader, a<meta charset>tag in HTML, or the encoding declaration of an XML file. Declarations are sometimes wrong, for instance when a file was converted and its header was not. - Validity: a file that is not valid UTF-8 is certainly not UTF-8.
- Statistical detection: the distribution of byte values and byte pairs differs characteristically among encodings and languages. Detectors such as the one built for the Mozilla browser compare a document's byte statistics with profiles of known encodings (Li and Momoi, 2001).
When decoding fails
What happens when this evidence is missing or wrong? Decoding errors take three common forms:
- Mojibake: valid text decoded with the wrong encoding, as in résumé. It produces plausible-looking garbage and passes every validity check.
- Replacement characters: a decoder that meets an invalid byte sequence can substitute U+FFFD, the replacement character (displayed as �). The text survives, but the affected words no longer match anything.
- Silent deletion: a decoder told to ignore errors drops the invalid bytes. résumé read as UTF-8 with errors ignored, from a file actually in Latin-1, becomes rsum.
All three can be produced from the two byte sequences that encode résumé, and their mechanics seen exactly. In UTF-8 it is the eight bytes shown at the top of this article. In Latin-1 it is six bytes, 72 E9 73 75 6D E9, with é as the single byte E9.
Example (mojibake, byte by byte). Given the UTF-8 pair C3 A9, a Windows-1252 decoder produces two characters, Ã for C3 and © for A9. Windows-1252 assigns a character to both bytes, as it does to nearly every byte value, so the decoder reports no error. The © is not a letter, so a tokenizer that keeps runs of letters treats it as a boundary, and résumé becomes two tokens, rã and sumã.
The table shows each failure and the tokens an indexer would then extract. It uses a tokenizer that lowercases and keeps runs of letters and digits:
| Bytes | Decoded as | Error handling | Text | Tokens indexed |
|---|---|---|---|---|
| UTF-8 | UTF-8 | résumé | résumé |
|
| UTF-8 | Windows-1252 | résumé | rã, sumã |
|
| Latin-1 | UTF-8 | replace | r�sum� | r, sum |
| Latin-1 | UTF-8 | ignore | rsum | rsum |
The other two failures come from the validity rule. The Latin-1 byte E9 is 11101001, which in UTF-8 announces a three-byte character. But the next byte, 73 (01110011, the letter s), does not begin with 10. The decoder must reject the sequence and either substitute U+FFFD or drop the byte.
The errors also compound. Text that has been mis-decoded once and saved again as UTF-8 can be mis-decoded a second time, and résumé becomes résumé. Each round makes the damage harder to reverse.
All three corrupt index terms without raising an error. A robust indexer therefore does three things:
- it records how each document was decoded;
- it counts decoding errors;
- it reports documents with many of them, since a sudden rise usually means a misidentified encoding rather than damaged files.
The pipeline article shows how a reasonable default in my own course code produced the third kind of failure.
Formats and text extraction
Correct characters are only useful if they are the right characters. Before text can be tokenized, it has to be extracted from the file format that contains it, and formats differ greatly in how much work that takes. The order of extraction and decoding depends on the format. An HTML file is decoded into characters before its markup is parsed. A PDF stores text in its own internal encodings that only the extractor can interpret.
Identifying the format usually relies on a declared type, a file extension or a MIME type such as application/pdf. That declaration is checked against the file's magic number, the signature in its first bytes:
- PDF files begin with
%PDF-. - Word, Excel, and PowerPoint files in their modern formats are ZIP archives that contain XML documents. They begin with the bytes
PK.
Extensions are easily wrong. The signature is much harder to fake by accident, though it can be ambiguous: PK identifies only a ZIP archive, not which format is inside. Careful systems check both.
Extracting text raises different problems in each format:
- HTML mixes content with markup, scripts, styles, and boilerplate: navigation menus, footers, advertisements, and links repeated on every page of a site. Indexing boilerplate makes every page of a site match the words in its menu. Boilerplate detection classifies blocks of a page as content or not, using shallow features such as text density and link density (Kohlschütter, Fankhauser, and Nejdl, 2010). HTML structure is also useful evidence. Titles, headings, and the anchor text of links can be indexed as separate fields and weighted more heavily in ranking. Markup languages also escape some characters as entities, such as
<for<and&for&. These must be decoded back into characters before tokenization. - PDF describes where glyphs appear on a page, not the order in which they should be read. Unless the file is tagged with its logical structure, extractors must reconstruct reading order. In a two-column paper, reading straight across the page interleaves the two columns line by line. Extractors must also rejoin words hyphenated across line breaks, drop running headers, footers, and page numbers, and map ligature glyphs such as fi back to their letters. A scanned PDF contains only images of pages. It needs optical character recognition, which introduces its own errors.
- Office documents are structured XML inside an archive, so their text is easier to extract. Embedded objects such as charts, images, and other documents need their own handling.
An extraction error in Reuters-21578
Undecoded entities give a concrete example of an extraction error that reaches the index. The Reuters-21578 newswire collection, as distributed with the NLTK toolkit, is used for experiments throughout this topic and this wiki. It still contains the SGML entity < wherever the original stories marked a company name with an angle bracket:
NATIONAL AMUSEMENTS AGAIN UPS VIACOM <VIA> BID
Viacom International Inc said <National
Amusements Inc> has again raised the value of its offer for
The entity occurs 8,694 times in 6,067 of the 10,788 stories. A tokenizer that keeps runs of letters turns every occurrence into the term lt. That term becomes the sixteenth most frequent in the collection and appears in 56 percent of the documents, more than most genuine words. The frequency chart in stop words shows it among the leaders.
The entity does no visible harm to a reader of the text. In an index it would go unnoticed unless someone looked at the most frequent terms, which is one of the cheapest checks an indexer can run. The numbers were computed by the script tools/experiments/textproc/delineation.py.
Metadata
Extraction should also collect metadata: title, author, creation date, and language where the format records them. Metadata supports fielded search and filtering. But embedded fields are often missing, stale, or inherited from a template (a report whose author is whoever created the template), so they need checking before they are trusted. General-purpose toolkits such as Apache Tika bundle format detection and extraction behind one interface. Tika's own description counts over a thousand file types.
Language identification
Once the text is out, the indexer needs to know which language it is in, because most later stages depend on it. A stop-word list, a stemmer, and a tokenizer for German are wrong for Finnish, and applying an English stemmer to French produces nonsense stems. The language of each document, and sometimes of each passage, must therefore be identified before those stages run.
Language identification is a classification problem, and short sequences of characters are strong evidence for it. Cavnar and Trenkle (1994) built a profile of each language from its most frequent character n-grams, typically sequences of one to five characters. They classified a document by comparing its own n-gram profile with each language's. Sequences such as th, ing, and the are characteristic of English, sch and ung of German, and ção of Portuguese. The method needs no dictionary and tolerates misspellings.
Later identifiers replaced the profile comparison with statistical or neural classifiers, but most still use character or byte n-grams as their features. Scripts give an even simpler first cut. Text in Cyrillic, Greek, Hangul, or Devanagari can be narrowed down from the Unicode code-point ranges alone.
The method worked through
Cavnar and Trenkle's procedure is simple enough to follow by hand (1994, §3.1 and §3.2). In plain words: count which short letter sequences a text uses, rank them, and pick the language whose ranking looks most alike.
N-grams. The text is split into tokens consisting only of letters and apostrophes. Each token is padded with a blank in front and blanks behind, written here as _, and every n-gram of one to five characters is taken from it. For the word text this gives the letters themselves and
bigrams _t te ex xt t_
trigrams _te tex ext xt_ t__
4-grams _tex text ext_ xt__ t___
5-grams _text text_ ext__ xt___ t____
The padding makes the beginnings and endings of words visible: _t records a word starting with t, and e_ a word ending in e.
Profiles. All n-grams in a text are counted and sorted by frequency, most frequent first, and only their order is kept. A language's profile is the top of this list for a sample of text in that language. Cavnar and Trenkle observed that the top 300 or so n-grams of a profile are almost always characteristic of the language. From about rank 300 onward, they begin to describe the subject of the text instead. In their language tests they compared profiles of 100 to 400 n-grams.
The reproduction here keeps 300. Profiles were built for nine languages from the first half of each language's translation of the Universal Declaration of Human Rights, about 5,000 characters each. The first entries of the English profile are the single letters e t n a o i r s h l, then e_, the end of a word in e. Single letters dominate the top of every profile. The n-grams that most distinguish languages come a little further down.
The out-of-place distance. A document's own profile is compared with each language profile. For every n-gram in the document's profile, the distance adds how far its rank there is from its rank in the language profile. An n-gram absent from the language profile adds a fixed maximum, here 300, the profile size; the paper leaves the exact value open. The language with the smallest total wins.
The sentence Everyone has the right to education. has 152 distinct n-grams. Here are the first eight, compared with the English and German profiles (ranks counted from 0):
| n-gram | Rank in sentence | English rank | Adds | German rank | Adds |
|---|---|---|---|---|---|
e |
0 | 0 | 0 | 0 | 0 |
t |
1 | 1 | 0 | 4 | 3 |
h |
2 | 8 | 6 | 7 | 5 |
o |
3 | 4 | 1 | 46 | 43 |
_e |
4 | 126 | 122 | 104 | 100 |
_t |
5 | 17 | 12 | absent | 300 |
a |
6 | 3 | 3 | 6 | 0 |
e_ |
7 | 10 | 3 | 27 | 20 |
Summed over all 152 n-grams, the distance is 20,332 to English and 33,797 to German. French is second-closest at 31,426.
Where does most of the difference come from? From absences. 44 of the sentence's n-grams are missing from the English profile and 103 from the German one, contributing 13,200 and 30,900. The method identifies a language mainly by which of its characteristic letter sequences a text contains, and only secondarily by how often.
Short texts and close relatives
The method has known weaknesses:
- Short texts. Accuracy falls sharply on very short texts, such as queries, social media posts, and titles, because they contain few n-grams (Baldwin and Lui, 2010).
- Close relatives. Closely related languages such as Spanish and Portuguese, or Malay and Indonesian, share many n-grams.
- Mixed documents. Many documents mix languages: an English paper quoting German, an email in Spanish with an English signature, a web page in Hindi with English navigation. Systems that care about such documents identify language per passage rather than per file.
The reproduction makes the first two weaknesses measurable. Snippets of whole words, at least a chosen number of characters long, were cut at random positions from the second half of each translation, which the profiles had not seen. Each snippet was classified among the nine languages. Each run classified 50 snippets per language at each length, and 30 runs with different random seeds give the spread.
Example (which languages are confused). At 20 characters, roughly the length of a search query, the classifier's mistakes are mostly between close relatives, not between more distant languages such as English and German. A short snippet contains few n-grams, and the ones it has are often shared by related languages. The counts follow the figure.
At 20 characters, about the length of a typical search query, the median accuracy is 85 percent (interquartile range 84 to 86). It rises to 97 percent at 400 characters. The most frequent errors are confusions between close relatives. At 20 characters, over the 30 runs, the three most frequent confusions were:
- Malay and Indonesian were mistaken for each other 996 times (507 in one direction and 489 in the other);
- Spanish was mistaken for Portuguese 234 times;
- German was mistaken for Dutch 71 times.
Even full sentences can be close calls. Setiap orang berhak mendapat pendidikan ('everyone has the right to education') is assigned to Malay with a distance of 25,808, against 26,289 for Indonesian. Every word in it is used in both languages.
These numbers come from small profiles, so they are lower than those of production identifiers trained on far more text. The shape is general, though. Cavnar and Trenkle reported 99.8 percent accuracy on Usenet articles using profiles of 400 n-grams (§4.3), and they found accuracy only slightly lower for articles under 300 bytes. Articles of that size are still long compared with a query. The script that produced the figure, tools/experiments/textproc/delineation.py, also prints the full distance tables.
What counts as a document
The text is now decoded, extracted, and labeled with a language. One decision remains: the document unit, what the index treats as one retrievable item. It is easy to take for granted that one file is one document. But the right unit depends on what people want returned. Manning, Raghavan, and Schütze (2008, §2.1.2) give the first three of these cases, and the fourth is added here:
- An email may be one document, or its body and each attachment may be separate documents, or the message with all its attachments may be one. A mail archive file containing thousands of messages should certainly not be one document.
- A book as one document makes almost every query match it, somewhere among its hundreds of pages. Chapters, sections, or pages may be better units.
- A presentation exported as one HTML page per slide may need its pages recombined into a single document.
- A web page is usually one document, but a long page of frequently asked questions might be better treated as one document per question.
Example (a whole book as one document). A library that indexes each whole book as one document loses precision, not recall. The thesis student searches for arctic seabirds, and nearly every long book on polar science matches. In a book of several hundred pages, the two words are likely to appear somewhere, often chapters apart and unrelated. The matches are real but mostly useless. Cutting the books into chapters would make a match mean more.
The choice involves the familiar trade-off between precision and recall. If units are too large, a query matches documents in which its terms appear far apart and unrelated, and precision falls. If units are too small, the terms of a query may be spread across several units, none of which matches the whole query, and recall falls.
Passage retrieval offers a middle path, in either of two forms. A system can index passages as separate units. Or it can keep returning whole documents but score each one using its best-matching passages, so that a long document is credited for the part that actually discusses the query. Callan (1994) found that combining the best passage score with the whole-document score worked better than either alone.
Structured formats such as XML make units explicit, since the markup can identify articles, sections, and paragraphs. Current retrieval-augmented generation systems face the same decision under a different name. They split documents into chunks for embedding, and the argument above applies to the chunk as it does to any other unit: a chunk that is too large matches on terms that are far apart, and a chunk that is too small can separate the terms of one query.
Whatever the unit, each one receives a document identifier, the number used in postings lists throughout the inverted index. The mapping from identifiers back to files, pages, or messages must be stored alongside the index, so that results can be shown to the user.
Worked problems
Section 2.1 of the course text has no exercises, so these problems are posed on this article's own examples: the UTF-8 and UTF-16 layouts, the three decoding failures, and the n-gram profile method. Every result is checked in tools/experiments/textproc/delineation.py, which also confirms that the two bit layouts used here agree with Python's encoders for every Unicode code point.
Problem 1 (packing two code points). Encode ñ (U+00F1) and 😀 (U+1F600) in UTF-8, showing the bits.
Solution. Hexadecimal F1 is 11110001, eight bits. That is too many for the one-byte pattern's seven and fits the two-byte pattern's eleven. Padded on the left to eleven bits it is 00011110001, split five and six into 00011 and 110001. The bytes are 110 00011 (C3) and 10 110001 (B1): ñ is C3 B1.
Hexadecimal 1F600 is 1 1111 0110 0000 0000, seventeen bits, more than the three-byte pattern's sixteen. It takes the four-byte pattern, whose payload has $3 + 6 + 6 + 6 = 21$ positions. Padded to 21 bits it is 000011111011000000000, split three, six, six and six into 000, 011111, 011000 and 000000. The bytes are 11110 000 (F0), 10 011111 (9F), 10 011000 (98) and 10 000000 (80): 😀 is F0 9F 98 80, as in the encoding table.
Problem 2 (one word, four decodings). The word café is stored once in UTF-8 and once in Latin-1. Give the bytes of each. Then give the text and the index tokens that result when the UTF-8 bytes are read as Windows-1252, and when the Latin-1 bytes are read as UTF-8 with invalid sequences replaced and with invalid sequences ignored. The tokenizer lowercases and keeps runs of letters and digits.
Solution. The letters c, a, f are ASCII, hexadecimal 63, 61 and 66 in both encodings. The é is C3 A9 in UTF-8, as worked above, and the single byte E9 in Latin-1. So the UTF-8 form is 63 61 66 C3 A9, five bytes, and the Latin-1 form is 63 61 66 E9, four bytes.
| Bytes | Decoded as | Error handling | Text | Tokens indexed |
|---|---|---|---|---|
| UTF-8 | UTF-8 | café | café |
|
| UTF-8 | Windows-1252 | café | cafã |
|
| Latin-1 | UTF-8 | replace | caf� | caf |
| Latin-1 | UTF-8 | ignore | caf | caf |
In the second row, Windows-1252 reads C3 as à and A9 as ©. The à is a letter and joins the token, which lowercases to cafã. The © is not a letter and ends it. In the last two rows the byte E9 is 11101001, which announces a three-byte character, but the input ends before any continuation byte arrives. The decoder substitutes U+FFFD or drops the byte, and either way the token is caf. None of the three faulty readings produces a term that the query café or cafe would match. Here the two failures of the Latin-1 file give the same token, where résumé gave r, sum and rsum, because the damaged character is at the end of the word.
Problem 3 (mojibake twice). The UTF-8 bytes of résumé are read as Windows-1252, the result is saved as UTF-8, and those bytes are read as Windows-1252 again. Count the bytes and the characters at each stage.
Solution. résumé is 6 characters and 8 bytes in UTF-8: four ASCII letters and two bytes for each é.
First wrong reading. Each of the 8 bytes becomes one character, so the text résumé has 8 characters. Saved as UTF-8, the four ASCII letters take one byte each. à (U+00C3) and © (U+00A9) lie between U+0080 and U+07FF and take two bytes each: à is C3 83 and © is C2 A9. The file is now $4 + 4 \times 2 = 12$ bytes.
Second wrong reading. Each of the 12 bytes becomes one character, so the text has 12 characters. The four bytes C3 83 C2 A9 that stand for one é are read as Ã, ƒ,  and ©, since Windows-1252 assigns ƒ (U+0192) to the byte 83 and  to C2. The text is résumé, as in the section on decoding failures. All four of those characters again lie between U+0080 and U+07FF, so saved as UTF-8 the text takes $4 + 8 \times 2 = 20$ bytes.
One é therefore occupies 2, 4 and then 8 bytes, and the word 8, 12 and then 20 bytes and 6, 8 and then 12 characters. The doubling is a fact about these two rounds, in which every character produced happens to need two bytes. It is not a general rule.
Problem 4 (n-grams and the out-of-place distance). (a) Count the n-grams of one to five characters that the profile method takes from the word sea, and give a formula for a word of $k$ letters. (b) A document's profile ranks three n-grams e, t, a at ranks 0, 1, 2. Language A's profile is e, a, t, o at ranks 0 to 3, and language B's is a, n, e at ranks 0 to 2. An n-gram absent from a language profile adds that profile's size. Classify the document.
Solution. (a) The word contributes its 3 letters as unigrams. Padded as _sea____, it contributes for each length from 2 to 5 one n-gram starting at each of its first four positions:
bigrams _s se ea a_
trigrams _se sea ea_ a__
4-grams _sea sea_ ea__ a___
5-grams _sea_ sea__ ea___ a____
That is $3 + 4 \times 4 = 19$ n-grams, all different. A word of $k$ letters contributes $k$ unigrams and, for each of the four lengths from 2 to 5, one n-gram starting at the leading blank and one at each letter, $k + 1$ in all. The total is $k + 4(k+1) = 5k + 4$. For text, with $k = 4$, that is 24, which matches the 4 letters and the 20 longer n-grams listed in the section on the method. Only 23 of them are distinct, because the letter t occurs twice.
(b) To language A: e is at rank 0 in both and adds 0. t is at rank 1 in the document and 2 in A and adds 1. a is at rank 2 and 1 and adds 1. The distance is $0 + 1 + 1 = 2$. To language B: e is at ranks 0 and 2 and adds 2. t is absent from B and adds the profile size, 3. a is at ranks 2 and 0 and adds 2. The distance is $2 + 3 + 2 = 7$. The document is assigned to language A. As in the worked sentence, the largest single contribution comes from an n-gram that the losing profile lacks.
What we have learned
Before tokenization begins, a document has been decoded from bytes, extracted from its format, assigned a language, and cut into the units the index will return. Each of these steps can fail silently. The résumé that became rã and sumã, and the lt that sits in 56 percent of the Reuters stories, both entered an index without a single error message. The defense is cheap: record how each document was decoded, count errors, and look at the most frequent terms.
What comes out of this stage is a sequence of characters per document. An analyzer still has to cut that sequence into words, and even in English the cuts are not obvious. The next article, Tokenization, takes the decoded text and splits it into tokens. It establishes that O'Neill's, for example, has no single correct division: of the three rule-based tokenizers compared there, one leaves it whole, one makes two tokens of it, and one keeps only o and neill. The stemming article ends by following one sentence through every stage, from its bytes to its index terms.
References
- Baldwin, T., and Lui, M. (2010). Language identification: The long and the short of the matter. In Proceedings of NAACL-HLT 2010, 229–237. record
- Callan, J. P. (1994). Passage-level evidence in document retrieval. In Proceedings of SIGIR 1994, 302–310. record · 2 pages
- Cavnar, W. B., and Trenkle, J. M. (1994). N-gram-based text categorization. In Proceedings of the Third Annual Symposium on Document Analysis and Information Retrieval (SDAIR-94), 161–175. record
- Kohlschütter, C., Fankhauser, P., and Nejdl, W. (2010). Boilerplate detection using shallow text features. In Proceedings of WSDM 2010, 441–450. record
- Li, S., and Momoi, K. (2001). A composite approach to language/encoding detection. In Proceedings of the 19th International Unicode Conference. record
- Manning, C. D., Raghavan, P., and Schütze, H. (2008). Introduction to Information Retrieval, sections 2.1 and 2.2.1. Cambridge University Press. record · 102 pages
- Pike, R., and Thompson, K. (1993). Hello world or Καλημέρα κόσμε or こんにちは 世界. In Proceedings of the Winter 1993 USENIX Conference, 43–50. record
- The Unicode Consortium. The Unicode Standard, section 3.9, Unicode Encoding Forms. https://www.unicode.org/standard/standard.html record · 2 pages
- W3Techs (2026). Usage statistics of UTF-8 for websites. https://w3techs.com/technologies/details/en-utf8 (figure read on 16 November 2026). record
- Yergeau, F. (2003). UTF-8, a transformation format of ISO 10646. RFC 3629, Internet Engineering Task Force. record
Reviewed: verified, 16 Nov 2026 · citations checked, 16 Nov 2026 · editorial review, 23 Nov 2026 · 10 revisions