AI Hints
Home›RAG Tutorial›Cleaning and Chunking
RAG · Lesson 16 of 120

Cleaning Text

Tidy before you split.

⏱ 2 min read▶ Video at 15:34🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

Messy text makes search worse. Odd characters stop words from matching, and extra spaces waste room in the prompt. A little cleaning, before we split and embed, goes a long way.

Cleaning Text
From the video: Cleaning Text
  • Messy text
  • Worse search
  • Clean first

Cleaning the PDF text

Unicode data dot normalize, with the NFKC form, turns special characters, like the joined f i, back into normal letters. A regular expression squeezes runs of spaces and new lines into single spaces. Run it. The word first is fixed, and the text is one tidy line.

clean_text.pypython
import re, unicodedata
from pypdf import PdfReader

raw = PdfReader("data/rag/volt_pro_manual.pdf").pages[1].extract_text()

def clean(text):
    text = unicodedata.normalize("NFKC", text)
    return re.sub(r"\s+", " ", text).strip()

print("before:", repr(raw[:40]))
print("after: ", repr(clean(raw)[:40]))
Output
before: '1. Before your first ride\nCheck the tyre '
after:  '1. Before your first ride Check the tyre'

What to clean

Normalise special characters. Collapse extra white space. Remove repeated headers, footers, and page numbers. And drop boilerplate, like cookie banners on web pages. But keep meaningful structure, like headings, which help later.

keyvalue
Normaliseunicode NFKC
White spacecollapse it
Boilerplateremove it
Headingskeep them

Summary

Clean text before splitting. Normalise characters, collapse white space, and remove boilerplate, but keep headings. Next, why we split documents into chunks.

Key takeaways
  • NFKC
  • Collapse spaces
  • Keep headings
Next up: Why Chunk — small pieces find better