Python for AI Engineers · Part B · Lesson 17 of 26
Working with text and documents in Python: PDF, HTML, Markdown and chunking for RAG
Turn messy files into clean chunks for RAG: bytes and encodings, Unicode cleanup, regex extraction, splitting sentences, parsing Markdown by headings, HTML with BeautifulSoup and PDFs with pypdf, then token counting with tiktoken, chunking with overlap and metadata, and removing duplicates.
⏱ 45 min3 exercises that check your codeRuns in your browser
By the end you can
- Read text with the right encoding, and clean it: Unicode normalisation, smart quotes, control characters, whitespace
- Pull fields out of text with the
remodule, and split text into paragraphs and sentences - Extract clean text from Markdown, HTML (BeautifulSoup) and PDF (pypdf), keeping headings and page numbers
- Count tokens roughly and exactly with tiktoken, then chunk documents with overlap and metadata for RAG
- Remove exact and near-duplicate chunks before you embed them
1Bytes, str and encodings
A file on disk holds bytes. Python code works with str, a sequence of Unicode characters. An encoding is the rule that turns one into the other: text.encode("utf-8") gives bytes, data.decode("utf-8") gives text back. Java has the same split (byte[] and String, joined by a Charset); in JavaScript it is TextEncoder and TextDecoder.
UTF-8 is the encoding of the web and of almost every modern file, and it is what you want. The danger is decoding with the wrong encoding: often there is no error, just garbage text (called mojibake) that you then embed and search. Run this and look at each line.
import tempfile
from pathlib import Path
raw = "Café menu: crème brûlée, 4 €".encode("utf-8") # str -> bytes
print(raw[:6], len(raw), "bytes")
print(raw.decode("utf-8")) # bytes -> str with the right encoding
print(raw.decode("cp1252")) # wrong encoding: garbage, and no error
try:
raw.decode("ascii")
except UnicodeDecodeError as e:
print("ascii fails:", e.reason, "at byte", e.start)
print(raw.decode("ascii", errors="replace")[:6])
path = Path(tempfile.gettempdir()) / "menu.txt"
path.write_bytes(b"\xef\xbb\xbf" + raw) # UTF-8 with a BOM, as Excel and Notepad save it
print(repr(path.read_text(encoding="utf-8")[:4]))
print(repr(path.read_text(encoding="utf-8-sig")[:4]))
Expected output
b'Caf\xc3\xa9 ' 34 bytes Café menu: crème brûlée, 4 € Café menu: crème brûlée, 4 € ascii fails: ordinal not in range(128) at byte 3 Caf�� '\ufeffCaf' 'Café'
Line by line: b'Caf\xc3\xa9 ' is a bytes literal: é is two bytes in UTF-8, so 28 characters become 34 bytes. Decoding as cp1252 (the old Windows encoding) turns each of those bytes into its own wrong character: é. Decoding as ascii fails loudly, which is better than garbage. errors="replace" puts the � replacement character where a byte did not fit.
The last two lines read a real file. path.read_text(encoding="utf-8") is short for open(path, encoding="utf-8").read() from lesson 10. Files saved by Excel or Notepad often start with a BOM (three bytes, EF BB BF) that shows up as an invisible \ufeff at the start of your text. The utf-8-sig encoding removes it if it is there and reads normal UTF-8 otherwise.
Tip Always pass encoding="utf-8" to open() and read_text(). Without it, Python 3.12 uses the operating system's default, which is still a legacy encoding such as cp1252 on many Windows machines. For files whose encoding you truly do not know, the charset-normalizer package can guess it.
2Clean the text: Unicode, quotes, control characters, whitespace
Text copied from PDFs, web pages and Word files is full of things you cannot see: two different byte sequences for the same é, the fi ligature (one character that looks like f + i), no-break spaces, curly quotes, zero-width spaces and stray control characters. A search for "Café" or "five" then fails, and they waste tokens.
Unicode normalisation fixes the first group. unicodedata.normalize("NFC", s) joins a letter and its accent into one character. "NFKC" does that and replaces "compatibility" characters with plain ones: fi becomes fi, a no-break space becomes a space, … becomes .... The function below runs the usual cleanup steps in order.
import re
import unicodedata
# curly quotes and dashes -> plain ASCII (str.maketrans builds a char-to-char table)
PLAIN = str.maketrans({"‘": "'", "’": "'", "“": '"', "”": '"',
"–": "-", "—": "-"})
def clean(text: str) -> str:
text = unicodedata.normalize("NFKC", text) # one form for each character
text = text.translate(PLAIN)
text = text.replace("\r\n", "\n").replace("\r", "\n")
text = "".join(ch for ch in text # drop invisible control characters
if ch in "\n\t" or unicodedata.category(ch)[0] != "C")
text = re.sub(r"[ \t]+", " ", text) # runs of spaces and tabs -> one space
text = re.sub(r" *\n *", "\n", text) # no spaces around line breaks
text = re.sub(r"\n{3,}", "\n\n", text) # at most one empty line in a row
return text.strip()
messy = "“Smart” quotes — five spaces here…\x00\r\n\r\n\r\n\r\nCafé"
print(repr(messy))
print(repr(clean(messy)))
print("Café" == "Café", len("Café"), len("Café"))
print(unicodedata.normalize("NFC", "Café") == "Café")
Expected output
'\ufeff“Smart” quotes — five spaces\xa0here…\x00\r\n\r\n\r\n\r\nCafé\u200b' '"Smart" quotes - five spaces here...\n\nCafé' False 5 4 True
What each step does:
normalize("NFKC", text)gives every character one standard form, as described above.str.maketrans({...})builds a lookup table andtext.translate(table)replaces every character found in it, in one pass. NFKC does not touch curly quotes or dashes, so we map them ourselves."\r\n"(Windows) and"\r"(old Mac) line endings become"\n".unicodedata.category(ch)returns a two-letter class such asLu(upper-case letter) orCc(control). Classes that start withCare control, format, private-use and unassigned code points: things like\x00, the BOM and the zero-width space\u200bthat you never want in an index. We keep only newlines and tabs from that group.- The three
re.subcalls (regex replace, next section) squeeze spaces, trim each line and allow at most one empty line in a row, so paragraphs stay separate.
The last two lines show why normalisation matters: "Cafe\u0301" is e followed by a combining accent. It looks exactly like "Café", but it has 5 characters instead of 4 and == says they are different until you normalise.
Watch out NFKC is lossy: x² becomes x2 and full-width letters become normal ones. That is fine for text you embed and search, but keep the original for display. Removing every C character also drops the zero-width joiner used in some emoji and Indic scripts: test the cleanup on your own languages.
3Regex with re: extract, replace and split
Regular expressions work like in Java and JavaScript, with a few Python habits. Write patterns as raw strings, r"\d+", so the backslash reaches the regex engine untouched (no doubling as in Java). There are no /.../g literals: you call functions from the re module.
re.findall(p, s)returns every match as a list of strings (or just the group, if the pattern has one group).re.search(p, s)returns the first match anywhere as aMatchobject, orNone.re.matchonly matches at the start of the string, a classic surprise.re.finditergives every match as aMatchobject, with groups.(?P<name>...)is a named group, read withm["name"].re.compile(p)builds the pattern once, for reuse in a loop.re.sub(p, repl, s)replaces every match, andre.split(p, s)cuts the string at every match.
The second half of the example splits text. Paragraphs are separated by an empty line, which may contain spaces: \n\s*\n is a newline, any whitespace, another newline. Sentences are harder: the END pattern matches whitespace that comes after ., ! or ? and before a capital letter. Watch what it does with "Dr." and "e.g.".
import re
# Extracting: ids, emails, amounts, dates
text = """Ticket #4521 from asha.k@example.com on 2026-03-14: refund of $120.50 failed.
Ticket #4533 from ben@example.org on 2026-03-15: invoice INV-0098 is missing."""
EMAIL = r"[\w.+-]+@[\w-]+\.[\w.]+"
print(re.findall(r"#(\d+)", text)) # with a group, findall returns just the group
print(re.findall(EMAIL, text))
m = re.search(r"\$(\d+(?:\.\d\d)?)", text) # first match anywhere, or None
print(m.group(0), m.group(1), float(m.group(1)))
TICKET = re.compile(r"#(?P<id>\d+) from (?P<email>\S+) on (?P<date>\d{4}-\d{2}-\d{2})")
for m in TICKET.finditer(text): # every match, as Match objects
print(m["id"], m["date"], m["email"])
print(re.sub(EMAIL, "[email]", text.splitlines()[0]))
print(re.match(r"\d+", "Ticket 42"), re.search(r"\d+", "Ticket 42").group())
# Splitting: paragraphs at empty lines, sentences after . ! ?
doc = """Refunds take 5 to 7 days. Card refunds may take longer! Need help? Email us.
Dr. Rao approved the policy on 2 Jan. It covers all plans, e.g. Pro and Team.
The old policy (v1.2) is retired."""
paragraphs = [p.strip() for p in re.split(r"\n\s*\n", doc) if p.strip()]
print(len(paragraphs), "paragraphs")
END = re.compile(r"(?<=[.!?])\s+(?=[A-Z])") # whitespace after . ! or ? and before a capital
print(END.split(paragraphs[1])) # the naive split
ABBREVIATIONS = {"dr.", "mr.", "ms.", "e.g.", "i.e.", "etc.", "vs."}
def sentences(paragraph: str) -> list[str]:
out = []
for piece in END.split(paragraph):
if out and out[-1].split()[-1].lower() in ABBREVIATIONS:
out[-1] += " " + piece # we split after an abbreviation: glue it back
else:
out.append(piece)
return out
for p in paragraphs:
for s in sentences(p):
print("-", s)
Expected output
['4521', '4533'] ['asha.k@example.com', 'ben@example.org'] $120.50 120.50 120.5 4521 2026-03-14 asha.k@example.com 4533 2026-03-15 ben@example.org Ticket #4521 from [email] on 2026-03-14: refund of $120.50 failed. None 42 3 paragraphs ['Dr.', 'Rao approved the policy on 2 Jan.', 'It covers all plans, e.g.', 'Pro and Team.'] - Refunds take 5 to 7 days. - Card refunds may take longer! - Need help? - Email us. - Dr. Rao approved the policy on 2 Jan. - It covers all plans, e.g. Pro and Team. - The old policy (v1.2) is retired.
const ids = [...text.matchAll(/#(\d+)/g)].map((m) => m[1]); // g flag: every match
const money = text.match(/\$(\d+(?:\.\d\d)?)/); // first match, or null
for (const m of text.matchAll(/#(?<id>\d+) from (?<email>\S+)/g)) {
console.log(m.groups.id, m.groups.email);
}
const masked = text.replace(/[\w.+-]+@[\w-]+\.[\w.]+/g, "[email]"); Pattern ticket = Pattern.compile("#(?<id>\\d+) from (?<email>\\S+)"); // backslashes doubled
Matcher m = ticket.matcher(text);
while (m.find()) {
System.out.println(m.group("id") + " " + m.group("email"));
}
String masked = text.replaceAll("[\\w.+-]+@[\\w-]+\\.[\\w.]+", "[email]"); Extracting: Python writes a named group as (?P<name>...), with a P; the (?<name>...) form from Java and JavaScript is an error in Python 3.12. (?:...) is a group that does not capture, used here so .50 is optional without becoming its own result. re.match(r"\d+", "Ticket 42") is None because the string starts with a T, while re.search finds 42. In AI work you use this to pull ticket ids, dates and amounts out of documents as metadata, and to mask personal data (re.sub(EMAIL, "[email]", ...)) before text goes to a hosted model.
Splitting: (?<=...) (look-behind) and (?=...) (look-ahead) check the characters around the split point without consuming them, so the full stop stays on its sentence and the capital on the next. The naive split cuts "Dr." and "e.g." off as if they ended sentences. The sentences function repairs that: when the last word of the previous piece is a known abbreviation, it glues the next piece back on. out[-1] is the last item of the list, and .split()[-1] its last word. Real text has more cases (quotes, lists, numbered items), so for serious work use a library such as pysbd or spaCy. For RAG, sentences only need to be good enough to avoid cutting a chunk in the middle of one.
Tip Use regex for small, regular things: ids, dates, amounts. Do not parse HTML or JSON with regex; use a parser (BeautifulSoup, json). And when the field is fuzzy ("the customer's complaint"), ask a model for structured output instead.
4Markdown: split by headings
Markdown docs, READMEs and wikis are the friendliest input you will get: the headings already tell you the structure. Splitting by heading gives chunks that each talk about one topic, and the heading path ("Employee handbook > Leave > Carry over") is great metadata: it tells the model, and the person reading the citation, where the text came from.
The parser reads line by line. A line like ## Leave starts a new section: the number of # signs is the level, and path keeps the headings above it. A # inside a fenced code block is a shell comment, not a heading, so the parser tracks whether it is inside a fence.
import re
MD = """# Employee handbook
Welcome to the team.
## Leave
You get 24 days per year.
### Carry over
Unused days carry over until March 31.
## Expenses
Submit receipts within 30 days.
```bash
# a comment inside a code block, not a heading
make expense-report
```
"""
HEADING = re.compile(r"^(#{1,6})\s+(.+)$") # 1 to 6 # signs, a space, the title
def split_by_headings(md: str) -> list[dict]:
sections, path, lines = [], [], []
in_code = False
def flush(): # save the text collected so far
text = "\n".join(lines).strip()
if text:
sections.append({"heading": " > ".join(path), "text": text})
lines.clear()
for line in md.splitlines():
if line.startswith(("```", "~~~")): # a code fence opens or closes
in_code = not in_code
m = None if in_code else HEADING.match(line)
if m:
flush()
level = len(m.group(1))
del path[level - 1:] # forget headings at this level or deeper
path.append(m.group(2).strip())
else:
lines.append(line)
flush()
return sections
for s in split_by_headings(MD):
print(f"[{s['heading']}]")
print(" " + s["text"].replace("\n", " | "))
Expected output
[Employee handbook] Welcome to the team. [Employee handbook > Leave] You get 24 days per year. [Employee handbook > Leave > Carry over] Unused days carry over until March 31. [Employee handbook > Expenses] Submit receipts within 30 days. | | ```bash | # a comment inside a code block, not a heading | make expense-report | ```
Key lines:
HEADINGcaptures the#signs as group 1 and the title as group 2.flush()is an inner function (a closure from lesson 4): it reads and clears the outerlineslist.lines.clear()empties the same list object, so nononlocalis needed.line.startswith(...)accepts a tuple of prefixes and is true if the line starts with any of them, so a fence of three backticks or of three tildes flipsin_code.del path[level - 1:]deletes the list items from indexlevel - 1to the end. Meeting a level 2 heading keeps only the level 1 heading, then appends the new one.
This handles the common cases. For full Markdown (tables, nested lists, headings underlined with ===), use a real parser such as markdown-it-py, or the Markdown splitters in LangChain and LlamaIndex, which work the same way.
5HTML: BeautifulSoup
Web pages mix the content you want with menus, scripts, styles, cookie banners and footers. BeautifulSoup parses HTML into a tree you can search and edit, like the DOM in a browser (document.querySelector and friends) or jsoup in Java. Install it in a project with uv add beautifulsoup4==4.15.0; you import it as bs4. This box runs in your browser: the page loads BeautifulSoup for you the first time.
The recipe: parse, remove the parts that are never content, find the main area, then read the text block by block.
from bs4 import BeautifulSoup
HTML = """<html><head><title>Refund policy | Acme</title>
<style>p { color: #333 }</style></head>
<body>
<nav><a href="/">Home</a> <a href="/pricing">Pricing</a></nav>
<main>
<h1>Refund policy</h1>
<p>Refunds take <b>5 to 7</b> days.</p>
<h2>Cards</h2>
<p>Card refunds may take longer. See
<a href="/faq#cards">the FAQ</a>.</p>
<ul><li>Visa</li><li>Mastercard</li></ul>
</main>
<aside>Get our newsletter!</aside>
<footer>© 2026 Acme</footer>
</body></html>"""
soup = BeautifulSoup(HTML, "html.parser") # html.parser ships with Python
print(soup.title.get_text())
for tag in soup(["script", "style", "nav", "aside", "footer"]): # soup(...) = soup.find_all(...)
tag.decompose() # remove the tag and everything inside it
main = soup.find("main")
print([a["href"] for a in main.find_all("a")])
print(repr(main.get_text(separator="\n", strip=True)[:40])) # the naive way
blocks = []
for el in main.find_all(["h1", "h2", "h3", "p", "li"]):
text = " ".join(el.get_text().split()) # inner text, whitespace collapsed
if el.name.startswith("h"):
text = "#" * int(el.name[1]) + " " + text # keep headings as Markdown
elif el.name == "li":
text = "- " + text
blocks.append(text)
print("\n".join(blocks))
Expected output
Refund policy | Acme ['/faq#cards'] 'Refund policy\nRefunds take\n5 to 7\ndays.\n' # Refund policy Refunds take 5 to 7 days. ## Cards Card refunds may take longer. See the FAQ. - Visa - Mastercard
What the calls do:
BeautifulSoup(HTML, "html.parser")builds the tree with the parser that ships with Python.lxmlis a faster parser you can install and pass instead.soup.title.get_text()reads the text of the first<title>tag.soup.find("main")returns the first matching tag (orNone),find_allreturns all of them, anda["href"]reads an attribute like a dict key. CSS selectors work too:soup.select("main p").tag.decompose()deletes a tag from the tree, so its text never reaches your index. Here the removed tags sit outside<main>anyway, but many sites have no<main>and you end up reading the whole<body>, so removing first is the safe habit. Script tags matter most: their code is text to BeautifulSoup.
The naive get_text(separator="\n", strip=True) puts a newline between every piece of text, so the bold "5 to 7" lands on its own line, in the middle of a sentence. Reading one block at a time (h1, p, li...) keeps sentences whole, and writing headings back as # Markdown means the heading splitter from the previous section can chunk the page. One catch: find_all also finds blocks nested inside other blocks (a <p> inside an <li>), which would repeat text; on real sites pick the block tags that fit the site.
Tip Downloading pages is a separate step (httpx, lesson 11). Respect robots.txt and the site's terms, and store the raw HTML next to the cleaned text, so you can re-clean everything later without crawling again.
6PDF: extract text with pypdf
PDFs are the most common and the worst input. A PDF stores positioned pieces of text for printing, not paragraphs, so extraction is always a best guess: columns can interleave, headers and footers repeat on every page, words get split by hyphens at line ends. And a scanned PDF has no text at all, only images of pages.
pypdf is a pure Python library that reads PDFs. It does not run in this page, so make a small project and run it on your machine. If you do not have a PDF to try, this script uses the reportlab library to write a two-page handbook.pdf:
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
pages = [
["Leave policy", "Employees get 24 days of paid leave per year.", "Unused days carry over until March 31."],
["Expenses", "Submit receipts within 30 days.", "Meals are capped at 40 euros per day."],
]
c = canvas.Canvas("handbook.pdf", pagesize=A4)
for lines in pages:
y = 800 # PDF coordinates start at the bottom left; 800 is near the top
for line in lines:
c.drawString(72, y, line) # 72 points = 1 inch from the left edge
y -= 20
c.showPage() # finish this page, start the next
c.save()
print("wrote handbook.pdf")
Save it as make_sample_pdf.py and the extractor below as extract_pdf.py, in the same folder.
uv init docs-demo --python 3.12
cd docs-demo
uv add pypdf==7.2.0 reportlab==5.1.2
uv run python make_sample_pdf.py
uv run python extract_pdf.py handbook.pdf wrote handbook.pdf handbook.pdf: 2 pages page 1: 97 chars, starts with 'Leave policy' page 2: 78 chars, starts with 'Expenses'
import sys
from pypdf import PdfReader
def read_pdf(path: str) -> list[dict]:
reader = PdfReader(path)
pages = []
for number, page in enumerate(reader.pages, start=1):
text = page.extract_text()
pages.append({"source": path, "page": number, "text": text.strip()})
return pages
def main() -> None:
path = sys.argv[1]
pages = read_pdf(path)
print(f"{path}: {len(pages)} pages")
for p in pages:
if not p["text"]:
print(f" page {p['page']}: no text layer (scanned? needs OCR)")
continue
first_line = p["text"].splitlines()[0]
print(f" page {p['page']}: {len(p['text'])} chars, starts with {first_line!r}")
if __name__ == "__main__":
main() PdfReaderopens and parses the file. It reads the whole PDF structure, not the text yet.line 3reader.pagesis a list of pages.enumerate(..., start=1)numbers them from 1, like the page numbers a person sees, so citations match.line 9- Text of one page as a single
str, lines joined with\n. A page without a text layer returns an empty string.line 10 - Keep the **source and page number** with the text from the start. You need them later to cite the answer ("handbook.pdf, page 2").line 11
sys.argvis the command line: index 0 is the script, index 1 the first argument. Likeargs[0]in Java'smain.line 16- An empty string is falsy, so this catches pages with no text: usually a scan that needs OCR.line 20
- Runs
main()only when you start this file directly, not when another file importsread_pdffrom it.line 27
The first three commands create a project (lesson 1), enter it, and install the two libraries at the versions this page was tested with; uv add prints a few lines about the packages it installs. Then you make the sample and extract it. Try extract_pdf.py on a real PDF of your own and print a whole page: you will see the problems described above. Useful extras: passing extraction_mode="layout" to extract_text keeps the visual layout (good for tables), reader.is_encrypted and reader.decrypt(password) handle protected files, and for scanned pages you need OCR, such as ocrmypdf, which adds a text layer that pypdf can then read.
Watch out Text that repeats on every page (a header, "Page 3 of 40", a confidentiality notice) ends up in every chunk and makes unrelated chunks look alike. Strip lines that appear on most pages before chunking, or remove the duplicates afterwards (last section).
7Count tokens: a rough rule and tiktoken
Models measure text in tokens, not characters: context limits, prices and chunk sizes are all in tokens. A token is a common piece of a word: " days" with its leading space is one token, an unusual word is split into several. A tokenizer turns text into a list of token ids (integers) and back.
The quick rule is about 4 characters per token for English. It is fine for a rough budget but drifts on code and is far off for other languages. For an exact count with OpenAI models, use their tokenizer library, tiktoken. It does not run in the browser, so add it to the project from the previous section and save this as count_tokens.py:
uv add tiktoken==0.14.0
uv run python count_tokens.py 45 chars rough 11 tiktoken 11 52 chars rough 13 tiktoken 10 31 chars rough 7 tiktoken 11 48 chars rough 12 tiktoken 17 [133559, 3376, 9852, 1072, 13] ['Unused', ' days', ' carry', ' over', '.']
import tiktoken
def rough_tokens(text: str) -> int:
return max(1, len(text) // 4) # about 4 characters per token in English
enc = tiktoken.get_encoding("o200k_base") # the tokenizer of GPT-4o and newer OpenAI models
samples = [
"Employees get 24 days of paid leave per year.",
"Retrieval-augmented generation finds passages first.",
"def add(a, b):\n return a + b",
"कर्मचारियों को हर साल 24 दिन की छुट्टी मिलती है।",
]
for text in samples:
ids = enc.encode(text)
print(f"{len(text):3} chars rough {rough_tokens(text):3} tiktoken {len(ids):3}")
ids = enc.encode("Unused days carry over.")
print(ids)
print([enc.decode([i]) for i in ids]) - The rough rule: integer division by 4 (
//drops the remainder), and at least 1.line 5 o200k_baseis the encoding used by GPT-4o and later OpenAI models. The first call downloads its vocabulary file once and caches it, so it needs internet the first time.line 8- The same sentence in Hindi, to see how the count changes for another script.line 14
encodereturns alist[int]of token ids. Its length is the token count.line 17{len(text):3}pads the number to 3 characters, so the columns line up.line 18decode([i])turns one id back into its piece of text, so you can see where the tokenizer cut.line 22
The rough rule is spot on for the plain English sentence, a bit high for the long words, and too low for code (spaces and symbols) and for Hindi, where the same sentence needs half again as many tokens. Note the leading spaces in ' days': the space belongs to the token. Other model families use different tokenizers: tiktoken is exact only for OpenAI models. For Llama, Mistral or Qwen use the model's own tokenizer (the Hugging Face tokenizers library), or read the usage field the API returns after each call.
Tip Use exact counts where a limit is hard (the context window, a max chunk size for an embedding model) and the rough rule for estimates such as "how much will embedding these 10,000 pages cost". Keep a safety margin either way.
8Chunk for RAG: size, overlap and metadata
RAG (retrieval-augmented generation) finds the passages that answer a question and puts them in the prompt. You cannot embed a 40-page PDF as one vector: it would mean everything and nothing. So you cut documents into chunks of a few hundred tokens, embed each one, and search those.
Three ideas make chunks work. Fixed size: every chunk fits the embedding model and the prompt. Overlap: each chunk repeats the end of the previous one, so a fact that falls on a boundary is still whole in one of them. Metadata: every chunk keeps where it came from (source, page, heading) so you can filter, cite and update. Here size is counted in words to keep the example short; in a project you count tokens.
def chunk_words(text: str, size: int, overlap: int) -> list[str]:
"""Pieces of `size` words; each piece repeats the last `overlap` words of the one before."""
if not 0 <= overlap < size:
raise ValueError("need 0 <= overlap < size")
words = text.split()
step = size - overlap
chunks = []
for start in range(0, len(words), step):
chunks.append(" ".join(words[start:start + size]))
if start + size >= len(words): # this piece reached the end
break
return chunks
text = " ".join(f"w{i}" for i in range(1, 26)) # "w1 w2 ... w25"
for c in chunk_words(text, size=10, overlap=3):
print(c)
# Real chunks carry metadata, so an answer can cite "handbook.pdf, page 2"
pages = [
{"source": "handbook.pdf", "page": 1, "text": "Employees get 24 days of paid leave per year. Unused days carry over until March 31."},
{"source": "handbook.pdf", "page": 2, "text": "Submit receipts within 30 days. Meals are capped at 40 euros per day."},
]
def chunk_pages(pages: list[dict], size: int, overlap: int) -> list[dict]:
chunks = []
for page in pages:
for i, piece in enumerate(chunk_words(page["text"], size, overlap)):
chunks.append({
"id": f"{page['source']}:p{page['page']}:c{i}",
"source": page["source"],
"page": page["page"],
"text": piece,
})
return chunks
for c in chunk_pages(pages, size=10, overlap=2):
print(c["id"], "|", c["text"])
# By headings: split by section first (the Markdown section), then by size inside each one
sections = [
{"heading": "Handbook > Leave", "text": "You get 24 days per year."},
{"heading": "Handbook > Leave > Carry over", "text": "Unused days carry over until March 31."},
]
def chunk_sections(sections: list[dict], source: str, size: int, overlap: int) -> list[dict]:
chunks = []
for s in sections:
for i, piece in enumerate(chunk_words(s["text"], size, overlap)):
chunks.append({
"id": f"{source}:{s['heading']}:c{i}",
"source": source,
"heading": s["heading"],
"text": f"{s['heading']}\n{piece}", # the heading travels with the text
})
return chunks
for c in chunk_sections(sections, "handbook.md", size=50, overlap=10):
print(repr(c["text"]))
Expected output
w1 w2 w3 w4 w5 w6 w7 w8 w9 w10 w8 w9 w10 w11 w12 w13 w14 w15 w16 w17 w15 w16 w17 w18 w19 w20 w21 w22 w23 w24 w22 w23 w24 w25 handbook.pdf:p1:c0 | Employees get 24 days of paid leave per year. Unused handbook.pdf:p1:c1 | year. Unused days carry over until March 31. handbook.pdf:p2:c0 | Submit receipts within 30 days. Meals are capped at 40 handbook.pdf:p2:c1 | at 40 euros per day. 'Handbook > Leave\nYou get 24 days per year.' 'Handbook > Leave > Carry over\nUnused days carry over until March 31.'
How chunk_words works: range(0, len(words), step) gives the start index of each chunk, moving forward by size - overlap words, so each chunk starts 3 words before the previous one ended (w8, w9, w10 appear twice). The loop stops as soon as a chunk reaches the last word, so no tiny leftover chunk is made. raise ValueError is Python's IllegalArgumentException: an overlap as large as the size would never move forward.
chunk_pages takes the page dicts that read_pdf returned in the PDF section and gives every chunk an id and its source and page. A stable id like handbook.pdf:p2:c1 lets you replace the chunks of one file when it changes. chunk_sections does the same for the Markdown sections: it splits by heading first and by size only inside a section, and it writes the heading path into the chunk text, so the embedding knows that "Unused days carry over" is about leave.
Look at the PDF chunks: a fixed size cuts in the middle of sentences ("...per year. Unused"). Common upgrades: pack whole sentences (section 3) into a chunk until the token budget is full, and start a new chunk at every heading. Typical starting values are 200 to 500 tokens with 10 to 20 percent overlap; then measure retrieval quality on your own questions and adjust.
9Remove duplicate and near-duplicate chunks
The same paragraph often appears in several places: an FAQ copied into the help center, a policy repeated in two PDFs, a footer on every page. Duplicates waste embedding money and, worse, fill the top search results with the same text, pushing out the useful second fact.
Exact copies are easy: normalise the text (lower case, words only) and keep a set of hashes, like a HashSet<String> in Java. Near copies need a similarity score. The Jaccard similarity of two sets is the size of what they share divided by the size of everything in either. We compare sets of shingles: every run of 3 words in a row.
import hashlib
import re
def normalise(text: str) -> str:
return " ".join(re.findall(r"\w+", text.lower())) # lower case, words only
def shingles(text: str, n: int = 3) -> set[str]:
"""Every run of n words in a row: 'a b c d' -> {'a b c', 'b c d'}."""
words = normalise(text).split()
return {" ".join(words[i:i + n]) for i in range(max(1, len(words) - n + 1))}
def jaccard(a: set, b: set) -> float:
return len(a & b) / len(a | b) if a | b else 1.0 # shared / all, from 0.0 to 1.0
def dedupe(chunks: list[dict], threshold: float = 0.8) -> list[dict]:
seen, kept = set(), []
for c in chunks:
digest = hashlib.sha256(normalise(c["text"]).encode()).hexdigest()
if digest in seen:
print("exact copy: ", c["id"])
continue
sh = shingles(c["text"])
twin = next((k for k in kept if jaccard(sh, k["shingles"]) >= threshold), None)
if twin:
print(f"near copy: {c['id']} ~ {twin['id']} ({jaccard(sh, twin['shingles']):.2f})")
continue
seen.add(digest)
kept.append({**c, "shingles": sh})
return kept
BASE = "Refunds take 5 to 7 business days after we receive the returned item. Card refunds can take longer, depending on your bank."
chunks = [
{"id": "faq.html:c0", "text": BASE},
{"id": "help.html:c3", "text": BASE.upper().replace(".", "!")}, # same words, other case and marks
{"id": "policy.pdf:p2:c1", "text": BASE + " Acme policy, page 2."}, # same text plus a page footer
{"id": "policy.pdf:p3:c0", "text": "Annual plans are refunded for each unused full month."},
]
kept = dedupe(chunks)
print("kept:", [c["id"] for c in kept])
Expected output
exact copy: help.html:c3 near copy: policy.pdf:p2:c1 ~ faq.html:c0 (0.83) kept: ['faq.html:c0', 'policy.pdf:p3:c0']
The help-center copy differs only in case and punctuation, so its normalised text has the same SHA-256 hash: an exact copy. The PDF chunk has a footer added, so the hashes differ, but it shares 83 percent of its shingles with the FAQ chunk, which is above the 0.8 threshold. The annual-plans chunk is new and is kept.
New syntax: a & b and a | b are set intersection and union. next((k for k in kept if ...), None) returns the first item that matches, or None, like stream().filter(...).findFirst() in Java or find in JavaScript. {**c, "shingles": sh} copies a dict and adds a key, like {...c, shingles: sh} in JavaScript.
Comparing every chunk with every kept chunk is fine for thousands of chunks. For millions, the same idea is done with MinHash and locality-sensitive hashing (the datasketch package), which find likely pairs without comparing everything. You can also deduplicate by embedding similarity after embedding, which catches paraphrases too.
Tip One changed word in a short chunk moves a lot of 3-word shingles, so short chunks score lower. Tune the threshold on real examples from your data, and log what you drop.
Common mistakes
- Opening files without
encoding="utf-8", or decoding bytes with the wrong encoding, and embedding mojibake likeCaféwithout noticing. - Skipping cleanup: invisible characters, two forms of
éand curly quotes make exact matches and keyword search fail. - Calling
re.matchwhen you meantre.search(match only looks at the start), or writing patterns withoutr"...". - Calling
get_text()on a whole page: menus, scripts and footers end up in your index, and inline tags split sentences. - Assuming every PDF has text. Scanned pages return an empty string; check for it and send them to OCR.
- Chunking without overlap or metadata, so facts get cut at boundaries and answers cannot cite a source or page.
Practice
Write the code, then press Check. Your work is saved in this browser.
1Clean a messy string
Write clean_text(s) so that it: normalises with NFKC, turns the four curly quotes (‘ ’ “ ”) into straight ' and ", turns every run of whitespace (spaces, tabs, newlines, no-break spaces) into one space, and strips both ends.
def clean_text(s):
# normalise, straighten the quotes, collapse whitespace
return s.strip()
Hint
`unicodedata.normalize("NFKC", s)`, then `.translate(str.maketrans({...}))` for the quotes, then `re.sub(r"\s+", " ", s).strip()`.
2Chunks with overlap
Fix chunk_words(text, size, overlap). Each chunk holds up to size words and starts overlap words before the previous chunk ended; stop once a chunk reaches the last word. Raise ValueError unless 0 <= overlap < size. An empty text gives an empty list.
def chunk_words(text, size, overlap):
words = text.split()
# no overlap yet, and no check of the arguments
return [" ".join(words[i:i + size]) for i in range(0, len(words), size)]
Hint
Step forward by `size - overlap` words with `range(0, len(words), size - overlap)`, and `break` when `start + size >= len(words)`.
3Pull fields out of an invoice line
Write parse_invoice(line) that finds text like INV-0042 dated 2026-03-14, total $1,250.00 anywhere in line and returns {"number": "INV-0042", "date": "2026-03-14", "total": 1250.0}. The cents are optional and the amount may contain commas. Return None when there is no invoice in the line.
import re
def parse_invoice(line):
# find the number, the date and the total with one regex
return None
Hint
One compiled pattern with three named groups: `(?P<number>INV-\d+)`, `(?P<date>\d{4}-\d{2}-\d{2})`, `(?P<total>[\d,]+(?:\.\d\d)?)`. Escape the dollar sign as `\$`. Use `re.search`, and remove the commas before `float()`.
Interview questions
Q1How do you prepare documents for a RAG system?
Extract text per format (pypdf or OCR for PDFs, BeautifulSoup for HTML, a heading splitter for Markdown), clean it (encoding, Unicode normalisation, boilerplate like headers and menus), split it into chunks of a few hundred tokens with some overlap, attach metadata (source, page, heading, an id), remove duplicates, then embed and index. Keep the raw files so you can re-run the pipeline when you change any step.
Q2Why do chunks overlap, and how do you pick the chunk size?
Overlap keeps a fact that falls on a boundary whole in at least one chunk. Size is a trade-off: small chunks are precise but lose context, big ones carry context but dilute the embedding and use prompt space. Start around 200 to 500 tokens with 10 to 20 percent overlap, respect structure (headings, sentences), and tune it by measuring retrieval quality on real questions.
Q3What is the difference between NFC and NFKC normalisation?
Both make one standard form for characters that can be written in several ways, such as a letter plus a combining accent. NFC only joins or splits such pairs and keeps the meaning exact. NFKC also replaces compatibility characters with plain ones (ligatures, no-break spaces, full-width letters, superscripts), which is good for search and embeddings but loses some information.
Q4How do you get text out of a scanned PDF?
A scanned PDF only contains images, so text extraction returns nothing. Detect pages with empty text and run OCR, for example Tesseract through ocrmypdf, which adds a text layer; or use a document AI service or a vision model. Check OCR quality, since errors flow straight into retrieval.
Q5How do you count tokens, and why not just count characters?
Use the model's own tokenizer: tiktoken for OpenAI models, the Hugging Face tokenizer for open models, or the usage the API returns. Characters divided by 4 is a fair estimate for English prose but is off for code and badly off for many other languages, and context limits and prices are in tokens.
Q6How would you find near-duplicate chunks in a large corpus?
Normalise and hash to drop exact copies. For near copies, compare word shingle sets with Jaccard similarity; at scale, use MinHash with locality-sensitive hashing to find candidate pairs without comparing everything. Embedding similarity after indexing also catches paraphrases. Tune the threshold on real data and log what is removed.