Text Data
Reviews, support tickets, emails, chat messages, medical notes, product descriptions, source code: a large share of the world's data is text. Text is unstructured: a review has no fixed number of columns, two sentences with the same meaning can share no words, and one word can mean different things. Before a model can use text, it has to become numbers, and before that, you have to understand what you have.
What text looks like in code
In a table, text is just a column of strings. Some text columns are really categories (a country column with 30 distinct values); free text is the case where almost every value is different.
import pandas as pd
reviews = pd.DataFrame({
"review_id": [1, 2, 3, 4, 5],
"text": [
"Great kettle, boils fast. Love it!",
"Stopped working after 2 weeks :(",
"great KETTLE!!! fast fast fast",
"Lid is hard to open. Otherwise ok.",
"Café-style design, très chic",
],
"stars": [5, 1, 5, 3, 4],
})
reviews["n_chars"] = reviews["text"].str.len()
reviews["n_words"] = reviews["text"].str.split().str.len()
print(reviews[["review_id", "n_chars", "n_words", "stars"]])
print()
print("distinct texts:", reviews["text"].nunique(), "of", len(reviews)) review_id n_chars n_words stars
0 1 34 6 5
1 2 32 6 1
2 3 30 5 5
3 4 34 7 3
4 5 28 4 4
distinct texts: 5 of 5
Length in characters and words is the first thing to look at: it tells you about empty or truncated entries, and about how much a model will have to read.
Characters, encodings and Unicode
Computers store text as bytes, and an encoding maps characters to bytes. Today almost everything should be UTF-8, which can represent every Unicode character. Trouble starts when a file written in one encoding is read with another:
text = "Café-style design, très chic"
raw = text.encode("utf-8")
print("characters:", len(text), "| UTF-8 bytes:", len(raw))
print("read back as UTF-8: ", raw.decode("utf-8"))
print("read back as Latin-1:", raw.decode("latin-1"))characters: 28 | UTF-8 bytes: 30
read back as UTF-8: Café-style design, très chic
read back as Latin-1: Café-style design, très chic
The second line is mojibake: é became two strange characters because its two UTF-8 bytes were read as two Latin-1 characters. If you see é or ’ in a dataset, an encoding was mixed up somewhere upstream. Fix it at the source, with the right encoding= when reading the file, rather than patching strings later.
From text to numbers
There are three main families, which NLP & Transformers covers in depth:
| Approach | Idea | Example |
|---|---|---|
| Bag of words / counts | one column per vocabulary word, value = how often it appears | CountVectorizer, TF-IDF |
| Tokens | split into sub-word pieces with ids, the input of language models | tiktoken, BPE |
| Embeddings | a dense vector per text, close vectors for similar meaning | sentence-transformer models |
A bag of words is the simplest and shows the main point: each text becomes a row of a very wide, mostly zero table.
from sklearn.feature_extraction.text import CountVectorizer
texts = [
"Great kettle, boils fast. Love it!",
"Stopped working after 2 weeks :(",
"great KETTLE!!! fast fast fast",
]
vec = CountVectorizer()
X = vec.fit_transform(texts)
print("vocabulary:", list(vec.get_feature_names_out()))
print(X.toarray())
print("shape:", X.shape, "| non-zero share:", round(X.nnz / (X.shape[0] * X.shape[1]), 2))vocabulary: ['after', 'boils', 'fast', 'great', 'it', 'kettle', 'love', 'stopped', 'weeks', 'working']
[[0 1 1 1 1 1 1 0 0 0]
[1 0 0 0 0 0 0 1 1 1]
[0 0 3 1 0 1 0 0 0 0]]
shape: (3, 10) | non-zero share: 0.43
CountVectorizer lower-cased everything (so "Great" and "great", "Kettle" and "KETTLE" became the same word), dropped punctuation and one-character tokens such as "2", and counted "fast" three times in the third review. Those are choices, and each one changes what the model can see: dropping punctuation loses the :(, which is a strong signal in a review.
Even with three short texts, 57% of the table is zeros (the non-zero share is 0.43); with thousands of texts and a vocabulary of tens of thousands of words, well over 99% of it is.
Tokens for language models
Large language models do not read words or characters but tokens: pieces of words from a fixed vocabulary of tens of thousands of entries, learned from data with algorithms such as byte-pair encoding (BPE). Frequent English words are usually one token, while rare words, names, accented words and many non-English scripts split into several pieces. Even a simple rule-based split shows how much the choice of unit changes the count:
import re
text = "Café-style design, très chic!!!"
words = text.split()
word_punct = re.findall(r"\w+|[^\w\s]", text)
print(len(text), "characters")
print(len(words), "whitespace pieces:", words)
print(len(word_punct), "word/punctuation pieces:", word_punct)31 characters
4 whitespace pieces: ['Café-style', 'design,', 'très', 'chic!!!']
10 word/punctuation pieces: ['Café', '-', 'style', 'design', ',', 'très', 'chic', '!', '!', '!']
Token counts matter in practice because a model's input has a maximum length (its context window) and hosted models are billed per token. The NLP & Transformers course builds a BPE tokenizer from scratch and uses real ones.
Things to check in a text dataset
- Language(s): a model trained on English reviews will do poorly on French ones.
- Length distribution: empty strings, one-word answers, or texts cut at a fixed length (a sign of truncation by some system).
- Encoding problems: mojibake, HTML entities such as
&, invisible characters. - Duplicates and templates: copy-pasted spam, automatic messages ("Thank you for your order").
- Personal data: names, emails, phone numbers and addresses hide in free text. See Privacy, Consent, Licensing.
Practice
- A CSV of customer messages shows
I’minstead ofI'm. What happened, and what is the right fix?
Answer
The file is UTF-8 (the curly apostrophe is three bytes) but was read as Windows-1252/Latin-1, so each byte became its own character. Read the file again with encoding="utf-8" instead of repairing strings afterwards.
- Why can a bag-of-words model not tell "not good, bad" from "not bad, good"?
Answer
Both texts contain the same words with the same counts. Bag of words ignores order, so the two rows are identical. Models that use word order (n-grams, sequence models, transformers) can tell them apart.
Test yourself
What is mojibake?
- A Japanese text dataset
- Garbled characters from decoding bytes with the wrong encoding
- A tokenizer for emojis
- A type of missing value
A bag-of-words matrix for 10,000 reviews and a 20,000-word vocabulary is mostly…
- Ones
- Zeros
- Negative numbers
- Missing values
Why do token counts matter when you work with language models?
- They decide the file encoding
- Models have a maximum input length in tokens and services often charge per token
- Tokens are the same as characters
- They are only used for images