MODULE 2.7

📝 NLP and Text Processing

How to turn unstructured text—emails, support tickets, contracts, reviews—into data a program can use. You’ll tokenize, classify, extract entities, summarize, search by meaning, and, most importantly, measure how well your pipeline performs—all with Python code that runs on your machine.

7
Topics
~55
Minutes
Technical
Level
Practical
Type
0%
0 of 0 topics read · Section 1 of 7

Detailed content

1

🔤 Turn text into data

NLP (Natural Language Processing, or natural language processing, is a set of techniques that lets a program read, organize, and produce human language. The starting problem is always the same: a computer only works with numbers. Before it can classify a complaint or summarize a contract, text has to become a sequence of numbers—and every choice in that conversion affects the result later on.

Until around 2018, NLP work was dominated by rules and small models trained for a single task. Today, an LLM can do almost anything with a well-written instruction. But the fundamentals still apply: tokens cost money and fit within a limited window, messy text produces messy answers, and the same word can mean different things depending on the context.

📘 New terms

Tokenization means breaking text into pieces (tokens) from the model’s vocabulary. Today’s models use subwords, generated by algorithms such as BPE (Byte Pair Encoding): common words become one token; rare words are split into parts. Normalization means standardizing text before processing it—spaces, line breaks, capitalization, and invisible characters.

What it is

The path is text → tokens → numeric IDs → vectors. The vectors (embeddings) carry the meaning the model has learned; everything that comes next—classification, extraction, search—operates on them.

raw text “I didn’t like the shipping” tokens I · didn · ’t like · the · shipping IDs [812, 4471, 91, …] embeddings [0.12, −0.48, 0.07, …] what you read what the model reads position in the vocabulary meaning in numbers illustrative splits and numbers—each model has its own vocabulary
How to read: follow from left to right. The first two frames are still text; the last two are numbers. Notice that “gostei” became two tokens: inflected Portuguese words often use more tokens than their English equivalents, which affects cost and the context window.

✓ Always normalize

  • ✓Unicode in NFC form (composed and decomposed accents become the same).
  • ✓Repeated spaces, tabs, and extra line breaks.
  • ✓Email signatures, footers, and HTML that carry no meaning.
  • ✓Personal data that doesn’t need to go to the model (LGPD, Module 2.9).

✗ Don’t destroy the signal

  • ✗Removing accents: “pais” and “país” are no longer different.
  • ✗Removing “não” as a stop word: the sentence reverses its meaning.
  • ✗Converting everything to lowercase when acronyms and names matter.
  • ✗Removing emojis from reviews: they often carry the sentiment.

💡 Tip

With LLMs, aggressive cleaning with older techniques (stemming, removing stop words) does more harm than good. Clean up formatting noise and personal data; leave the language as it is.

Why learn

Understanding tokens explains the bill that arrives at the end of the month, why a document “doesn’t fit” in the context window, and why poorly cleaned text confuses the model. It’s the foundation for sizing any text pipeline before writing the first line of code.

Key concepts

Token
piece of the vocabulary
Subword (BPE)
rare word becomes parts
Normalization
standardize without losing meaning
Embedding
meaning as a vector
2

🏷️ Classify text

Text classification means assigning each text a label from a closed list: the subject of a support ticket, the sentiment of a review, the urgency of an email, whether a message is spam. It’s the most common NLP task in businesses because it lets you route, count, and prioritize without anyone reading everything.

There are three approaches. The classic turns text into word counts (TF-IDF) and trains a simple model, such as logistic regression in scikit-learn—fast and inexpensive, but it needs hundreds of labeled examples. The fine-tuning of a small model (from the BERT family) delivers high quality, with training costs. And zero-shot with an LLM classifies using only the label list and an instruction, with no training at all.

📘 New terms

TF-IDF weights each word by its frequency in the text and its rarity across the entire dataset. Zero-shot means doing the task without examples; few-shot means including a few examples in the prompt itself. Structured output means requiring the model to respond in a machine-readable format, such as JSON.

What it is

A function that takes text and returns a label from a list you define, preferably with a short explanation and in a format the rest of the system can validate.

ApproachRequiresBest whenCaution
TF-IDF + linear modelHundreds of labeled examplesHigh volume, stable labels, minimal costDoesn’t understand synonyms or irony
Fine-tuning (BERT and similar models)Labeled examples and a GPUHigh quality with low latencyRetraining for every new label
Zero-shot/few-shot LLMA list of labels and a good instructionGetting started today, changing labelsCost and latency per item; validate the output

Try this: local zero-shot classifier, saved as classifier.py.

# Installation: pip install openai   |   ollama pull qwen2.5:7b
# classifier.py — uses Ollama's OpenAI-compatible route (local and free)
import json
from openai import OpenAI

client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")  # Ollama ignores the key
LABELS = ["delivery", "payment", "product", "compliment", "other"]

INSTRUCTION = (
    "You classify messages from customers of an online store. "
    'Respond ONLY with JSON in the format {"label": "...", "reason": "..."}. '
    "Valid labels: " + ", ".join(LABELS) + ". "
    "Use 'other' when none applies. The reason must be no more than 12 words."
)

def classify(text: str) -> dict:
    resp = client.chat.completions.create(
        model="qwen2.5:7b",
        temperature=0,                              # same input, same output (almost always)
        response_format={"type": "json_object"},    # forces valid JSON
        messages=[{"role": "system", "content": INSTRUCTION},
                  {"role": "user", "content": text}],
    )
    data = json.loads(resp.choices[0].message.content)
    if data.get("label") not in LABELS:           # never blindly trust the output
        data["label"] = "other"
    return data

if __name__ == "__main__":
    print(classify("<paste a real customer message here, without personal data>"))

How to check: run python3 classificador.py. The output should be a dictionary like {'rotulo': 'entrega', 'motivo': '...'}. Test five messages with different labels and one that has nothing to do with the store: it should be classified as "outro". To use a paid API, change only base_url, api_key e model.

💡 Tip

Start with the LLM to identify the right labels and gather examples. As volume grows and the labels stabilize, use responses reviewed by people to train a small, inexpensive classifier. This is a common way to reduce costs without losing quality.

Why learn

Almost every customer support, triage, or sentiment analysis system starts with classification. Knowing how to choose between the classic approach, fine-tuning, and an LLM—and how to validate the output—helps you avoid both an overly expensive project and one that breaks on the first response in the wrong format.

Key concepts

Closed list
labels you define
Zero-shot
no training examples
JSON output
the system can read it
Validation
a label outside the list becomes "outro"
3

🧾 Extract entities

NER (Named Entity Recognition, finding people’s names, companies, places, dates, and amounts in text, and identifying the type of each. With this, a contract becomes a spreadsheet row: parties, amount, term, jurisdiction. A news story becomes a list of the companies mentioned.

There are two families of tools. Libraries like spaCy include ready-to-use models for Portuguese (pt_core_news_sm) that quickly identify people, places, and organizations at no cost. For fields specific to your business (order number, product name, penalty clause), an LLM with a JSON schema is usually more flexible: you describe the fields, and the model fills them in.

📘 New terms

JSON Schema is a formal description of a JSON’s fields, types, and required properties. Ollama accepts this schema in the format parameter and constrains generation so the response fits it. BIO tags (Begin, Inside, Outside) is the classic way to mark entities word by word when training NER models.

What it is

Information extraction: find passages with specific meanings in free-form text and return them organized by type, ready to go into a database or another pipeline step.

input text "Loja Sol hired Ana Lima in São Paulo for R$ 4.000 on 03/02/2026." ORGANIZATION Loja Sol PERSON Ana Lima LOCATION São Paulo AMOUNT R$ 4.000 DATE 03/02/2026 JSON record → database or spreadsheet
How to read: The sentence above is the input; each card is a passage copied from the sentence with its type. Notice that none of the cards contains information that wasn't in the text—that's what your code needs to check, because an LLM may "fill in" an empty field with something plausible.

Goal: extract entities with a JSON schema and check that nothing was made up.

# Installation: pip install requests   |   ollama pull qwen2.5:7b
import json, requests

CAMPOS = ["pessoas", "organizacoes", "locais", "datas", "valores"]
SCHEMA = {
    "type": "object",
    "properties": {c: {"type": "array", "items": {"type": "string"}} for c in CAMPOS},
    "required": CAMPOS,
}

def extrair(texto: str) -> dict:
    r = requests.post("http://localhost:11434/api/chat", json={
        "model": "qwen2.5:7b",
        "stream": False,
        "format": SCHEMA,                 # the response is restricted to this schema
        "options": {"temperature": 0},
        "messages": [
            {"role": "system", "content": "Extract the entities from the text. Copy each passage "
             "exactly as it appears. Don't make anything up: use an empty list when there are none."},
            {"role": "user", "content": texto},
        ],
    }, timeout=120)
    r.raise_for_status()
    return json.loads(r.json()["message"]["content"])

texto = "<paste a paragraph from a contract, news story, or email>"
ents = extrair(texto)
print(json.dumps(ents, ensure_ascii=False, indent=2))

# Anti-fabrication check: every passage must appear literally in the text
for tipo, itens in ents.items():
    for item in itens:
        if item not in texto:
            print(f"WARNING [{tipo}] is not in the text: {item!r}")

How to check: With the sentence from the diagram, the output should have all five lists filled and no "WARNING" line. Then paste text with no dates: dates it should come back empty. If a warning appears, the model rewrote or made up a passage—treat that as an error, not a success.

💡 Tip

For standard entities at scale, try spaCy first: pip install spacy e python -m spacy download pt_core_news_sm. It runs on CPU, with no GPU, and serves as a baseline for comparison with the LLM.

Why learn

Much of the value of NLP in companies comes from extracting data from documents: receipts, contracts, medical reports, résumés, and emails. Knowing how to extract data using a schema and verify it against the original text is what separates a demo from a process you can trust.

Key concepts

NER
names with types
JSON Schema
the required format
Grounding
passage appears in the text
spaCy
ready-to-use NER, on CPU
4

📄 Summarize long texts

Summarizing seems simple until a document runs to dozens of pages. Even with large context windows, models tend to pay less attention to the middle of very long texts, and a single summary hides where each claim came from. The robust method is to split, summarize the parts, and then combine them, keeping a reference for each passage.

There are two types of summary. An extractive summary selects sentences from the original and copies them—safe because nothing is rewritten. An abstractive summary rewrites the text in other words—more fluent, but it can distort the meaning. For legal, medical, or financial texts, a middle ground works well: an abstractive summary with direct quotes from the passages that support each point.

📘 New terms

Chunking is to divide the document into passages (chunks) of a controlled size, preferably following sections and paragraphs. Overlap (overlap) is repeating part of the end of one passage at the beginning of the next so an idea isn't cut in half. Map-reduce means applying the same operation to each passage (map) and then combining the results (reduce).

What it is

Summary in stages: the document is divided into passages, each passage gets a partial summary with a reference to its source, and finally a final summary combines the partial summaries in the format the reader needs.

INPUT 1 · SPLIT 2 · MAP 3 · REDUCE document long passage 1 · p. 1–8 passage 2 · p. 8–16 passage 3 · p. 16–24 passage 4 · p. 24–30 summary 1 + source summary 2 + source summary 3 + source summary 4 + source final summary in the reader's format
How to read: The columns are stages. Each partial summary carries the page it came from, and the final summary can only use what's in the partial summaries. When someone asks "where did this come from?" you can follow the lines back to the passage. The map steps can run in parallel.

For decision-makers

Five points, with risks first, each with its source page. End with "what remains to be decided."

For implementers

List obligations, deadlines, and owners in a table. No long paragraphs.

For the system

JSON with fixed fields (topic, parties, dates, amounts) for indexing and filtering later.

💡 Tip

Split by structure (headings, clauses, sections), not by a fixed number of characters. A cut in the middle of a clause produces two incorrect partial summaries.

Why learn

Reports, meeting minutes, case files, and manuals are long and read in a hurry. A traceable summary saves hours of reading without hiding where each conclusion came from—and the same pattern of splitting, processing, and combining works for translation, extraction, and review of large documents.

Key concepts

Extractive
copies sentences from the original
Abstractive
rewrites in different words
Chunking
sections by structure
Map-reduce
summarize sections, then combine them
5

🔎 Semantic search

Keyword search only finds content that uses the same word. Someone who asks “my package hasn’t arrived” won’t find the text “delivery time”—even though that’s exactly what they’re looking for. Semantic search compares meanings: it turns the question and documents into vectors and returns the documents whose vectors are closest.

This is the central part of RAG (retrieval-augmented generation), covered in the module on knowledge bases: before answering, the system searches for relevant passages and provides them to the LLM. In production, the vectors are stored in a dedicated database— pgvector in Postgres, Qdrant or Chroma. To learn, a NumPy array is enough.

📘 New terms

Cosine similarity measures the angle between two vectors: near 1, they point in the same direction (similar meanings); near 0, they’re unrelated. If the vectors are normalized (length 1), the cosine becomes a simple dot product. Hybrid search combines keywords and vectors, useful when exact codes and names matter.

What it is

Search by similarity of meaning: an embedding model converts texts into vectors, and the query returns the texts closest to the question by cosine similarity, even when they have no words in common.

2D projection of vectors with hundreds of dimensions (for illustration) delivery and shipping payments and bills compliments question: “my package hasn’t arrived” closest
How to read: Each point is a text; texts on the same subject cluster together, even when they use different words. The star is the question: the search returns the points in the closest cluster. The 2D projection is only for visualization—the actual distance is calculated across all dimensions.

Try this: local semantic search with nomic-embed-text.

# Installation: pip install requests numpy   |   ollama pull nomic-embed-text
import requests
import numpy as np

def embed(textos: list[str]) -> np.ndarray:
    r = requests.post("http://localhost:11434/api/embed",
                      json={"model": "nomic-embed-text", "input": textos}, timeout=120)
    r.raise_for_status()
    v = np.array(r.json()["embeddings"], dtype=float)
    return v / np.linalg.norm(v, axis=1, keepdims=True)   # normalize: cosine = dot product

# nomic-embed-text recommends different prefixes for documents and queries
docs = [
    "The delivery time is 5 to 10 business days after payment is confirmed.",
    "Expired bills can be reissued in the customer area.",
    "Returns are accepted within 7 calendar days after receipt.",
    "<add passages from your own knowledge base here, one per item>",
]
D = embed(["search_document: " + d for d in docs])

def buscar(pergunta: str, k: int = 2) -> None:
    q = embed(["search_query: " + pergunta])[0]
    notas = D @ q
    for i in np.argsort(-notas)[:k]:
        print(f"{notas[i]:.3f}  {docs[i]}")

buscar("my package still hasn’t arrived")

How to check: The first result should be the sentence about delivery time, even though it doesn’t contain the word “package.” Change the question to “can I return the T-shirt?”—the sentence about returns should move to the top. Scores vary from model to model; compare the ranking, not the absolute value.

Why learn

Semantic search is the foundation of assistants that answer using company documents, ticket deduplication, and content recommendations. Understanding the vector and the metric helps you diagnose why a search fails—before blaming the LLM for a bad answer.

Key concepts

Embedding
text as a vector
Cosine
similarity of meaning
Vector database
pgvector, Qdrant, Chroma
Hybrid search
keyword + vector
6

🌍 Portuguese and other languages

Most of the training data for models is still in English. Today’s LLMs handle Portuguese well, but differences still arise: more tokens for the same content, slang and regional expressions being misinterpreted, confusion between Brazilian and European Portuguese, and errors with local formats—CPF, CEP, dates in day/month format, decimal commas, “R$ 1.234,56.”

For translation, you have open, dedicated models such as NLLB from Meta, and general-purpose LLMs, which translate well and also follow tone and glossary instructions. For systems that receive text in multiple languages, the standard approach is to detect the language first and decide whether to process it in the original language with a multilingual model or translate it first.

📘 New terms

A multilingual model is trained on several languages at once and places equivalent sentences close together in embedding space—so a question in Portuguese can find a document in Spanish. A glossary, in translation, is a list of terms that should always be translated the same way (or left untranslated, such as product names).

What it is

It means treating language and local formats as part of the problem: detect the language, choose the right model and prompt, standardize numbers, dates, and Brazilian documents, and test with real texts from your audience.

✓ Works well

  • ✓Explicitly request “Brazilian Portuguese” in the system prompt.
  • ✓Convert “R$ 1.234,56” and “03/02/2026” with code, not the model.
  • ✓Validate CPF and CNPJ using the check digit after extraction.
  • ✓Use a fixed glossary in the translation prompt for company terms.

✗ Common pitfalls

  • ✗Test only with English text and publish for Brazilian customers.
  • ✗Let the model interpret “02/03” without knowing the date format.
  • ✗Ignore text with typos and WhatsApp abbreviations.
  • ✗Translate first and then extract, losing original names and values.

💡 Tip

Build your test set with messages written the way your customers actually write—with “vc,” “pq,” typos, and transcribed audio. Models that perform well on clean text can do much worse on informal text, and only testing shows how much.

Why learn

Examples, tutorials, and benchmarks are often in English. Anyone building for a Brazilian audience needs to know the typical failure points in Portuguese and local formats—that’s where a system that “worked in testing” breaks with its first real customer.

Key concepts

Language detection
first pipeline step
Multilingual
multiple languages in the same space
Local format
dates, currency, CPF
A glossary
terms that are always the same
7

🧪 Pipeline and evaluation

A text pipeline chains together the steps in this module: normalize, detect language, classify, extract, validate, and record. Each step has defined inputs and outputs, and each can fail. Without measuring, you don’t know which step failed or whether a model or prompt change improved or worsened the result.

The tool for this is the test set: a few dozen real, anonymized examples with the correct answer labeled by a person. Run every change against it. The resulting number doesn’t need to be perfect; it needs to be comparable across versions.

📘 New terms

Accuracy is the fraction of correct predictions out of the total. Precision for a label: of the items the model assigned that label, how many were correct. Recall (Recall): of the items that actually belonged to that label, how many the model found. F1 combines the two. With imbalanced classes, look at precision and recall for each label, not just accuracy.

What it is

A sequence of text processing steps with defined input and output contracts, tracked with a labeled test set that measures every change before it reaches users.

Step 1 · Gather real examples. Start with 30 to 50 anonymized messages covering all labels and difficult cases.

Step 2 · Label the correct answer. Having two people label the same sample reveals where the labels themselves are ambiguous.

Step 3 · Measure the current version. Run the script below and save the result as your baseline.

Step 4 · Change one thing at a time. Prompt, model, or step. Measure again and compare with the baseline.

Step 5 · Review the errors. The error list teaches you more than the number: ambiguous label, informal text, missing context.

Goal: measure the classifier from Topic 2 with a test set (evaluate.py).

# evaluate.py — save in the same folder as classifier.py (Topic 2)
from collections import Counter
from classificador import classificar

TESTE = [  # (text, correct label) — replace with 30+ real, anonymized examples
    ("My order has been stuck with the carrier for a week", "entrega"),
    ("The payment slip expired and I can't generate another one", "pagamento"),
    ("The T-shirt arrived with an open seam", "produto"),
    ("Excellent service, they resolved it in minutes", "elogio"),
    ("Are you open on the holiday?", "outro"),
    ("<real text>", "<correct label>"),
]

tp, fp, fn = Counter(), Counter(), Counter()
erros = []
for texto, certo in TESTE:
    previsto = classificar(texto)["rotulo"]
    if previsto == certo:
        tp[certo] += 1
    else:
        fp[previsto] += 1
        fn[certo] += 1
        erros.append((texto, certo, previsto))

total = len(TESTE)
acertos = sum(tp.values())
print(f"accuracy: {acertos}/{total} = {acertos / total:.0%}")
for r in sorted({c for _, c in TESTE}):
    prec = tp[r] / (tp[r] + fp[r]) if tp[r] + fp[r] else 0.0
    rev = tp[r] / (tp[r] + fn[r]) if tp[r] + fn[r] else 0.0
    print(f"{r:10s} precision={prec:.2f}  recall={rev:.2f}")
for texto, certo, previsto in erros:
    print(f"ERROR  expected={certo:10s} got={previsto:10s} | {texto}")

How to check: run python3 avaliar.py (delete the example line with < > first). You should see the accuracy, one line per label, and the error list. Change the prompt in classifier.py, run it again, and compare: if accuracy improves but one label gets worse, the change isn’t a complete win.

💡 Tip

Keep the test set in the repository alongside the code. In Module 2.8, it becomes an automatic gate: no version goes to production if its result falls below the baseline.

Why learn

Without a test set, every prompt adjustment is a guess and every model switch is a risk. With one, you can switch to a cheaper model knowing how much quality you lose, prove the improvement to your team, and catch errors before they reach customers.

Key concepts

Test set
examples with the correct answers
Baseline
the score to beat
Precision × recall
correct predictions by label
Error analysis
review what failed

✅ Module summary

✓
Text becomes tokens, IDs, and vectors — normalize the format, preserve the language.
✓
Classify and extract with structured output — validate the label and check each excerpt against the text.
✓
Summarize in steps and search by meaning — map-reduce with sources and normalized embeddings.
✓
Test with real Portuguese and measure everything — test set, baseline, and error review.

Next module:

2.8 — MLOps and Production 🛠️