Lesson 5 of 16 · Ingestion
Loading Documents
Get clean text from PDFs, web pages and Word files for RAG: remove headers and page numbers, fix broken lines, keep metadata and avoid extraction mistakes.
- 7 min read
- Intermediate
- Reviewed
- Extract text from PDFs, web pages and other common formats
- Clean extracted text: headers, footers, page numbers and broken lines
- Keep metadata such as source, page and title with every document
- Spot the formats that need special care, such as tables and scans
Garbage in, garbage out
Retrieval can only find what ingestion produced. If the text is full of page numbers, menus and words broken in half, chunks get worse, embeddings get noisier, and answers suffer. Loading is unglamorous, and it's where many RAG projects quietly lose quality.
Common formats
| Format | Common Python tools | Watch out for |
|---|---|---|
pypdf, pdfplumber, PyMuPDF | Headers and footers on every page, broken lines, tables, scanned pages with no text | |
| Web page (HTML) | BeautifulSoup, Python's built-in html.parser | Menus, cookie banners, footers and scripts mixed in with content |
| Word (.docx) | python-docx | Tables and headings need handling separately |
| Markdown, text | Plain open() | Usually the cleanest source; keep the headings |
| Spreadsheets, CSV | csv, pandas | Rows need turning into sentences or kept as structured data |
Reading a PDF page by page with pypdf, keeping the page number for citations later:
from pypdf import PdfReader
reader = PdfReader("handbook.pdf")
documents = []
for number, page in enumerate(reader.pages, start=1):
documents.append({"source": "handbook.pdf", "page": number, "text": page.extract_text()})Cleaning PDF text
Here's what extracted PDF text often looks like, and a cleaning function for it:
import re
# Text as it often comes out of a PDF: running headers, page numbers,
# words broken across lines, and lines cut mid-sentence.
pages = [
"""ACME LTD - EMPLOYEE HANDBOOK
Remote work
You can work from home up to 3 days a week, with your man-
ager's agreement. Core hours are 10am
to 4pm.
Page 7""",
"""ACME LTD - EMPLOYEE HANDBOOK
Expenses
Claim expenses within 30 days in the finance app, with a
photo of each receipt.
Page 8""",
]
def clean_page(text):
lines = text.split("\n")
lines = [l for l in lines if l.strip() != "ACME LTD - EMPLOYEE HANDBOOK"] # running header
lines = [l for l in lines if not re.fullmatch(r"Page \d+", l.strip())] # page numbers
text = "\n".join(lines)
text = re.sub(r"-\n(\w)", r"\1", text) # join words split by a hyphen: man-\nager -> manager
text = re.sub(r"(?<![.:\n])\n(?=[a-z0-9])", " ", text) # join lines cut mid-sentence
return text.strip()
documents = []
for number, page in enumerate(pages, start=7):
documents.append({"source": "handbook.pdf", "page": number, "text": clean_page(page)})
for doc in documents:
print(f"--- {doc['source']}, page {doc['page']} ---")
print(doc["text"])The running header and the page numbers are gone, “man-” and “ager's” are joined again, and lines cut in the middle of a sentence are rejoined. The page number is kept as metadata instead, where it's useful for citations.
Getting the content out of web pages
On a web page, the useful text sits inside the page's main content, surrounded by navigation, scripts and footers. Keep only what's inside the main element:
import re
from html.parser import HTMLParser
page = """<html><head><title>Training budget</title><script>trackVisitor()</script></head>
<body><nav>Home | HR | IT | Finance</nav>
<main><h1>Training budget</h1>
<p>Every employee has a learning budget of <b>1,000 euros</b> per year.</p>
<p>Courses over 300 euros need your manager's approval.</p></main>
<footer>Copyright Acme Ltd</footer></body></html>"""
class MainText(HTMLParser):
"""Keep the text inside <main>, skipping scripts, menus and footers."""
def __init__(self):
super().__init__()
self.in_main = False
self.parts = []
def handle_starttag(self, tag, attrs):
if tag == "main":
self.in_main = True
def handle_endtag(self, tag):
if tag == "main":
self.in_main = False
if tag in ("p", "h1", "h2", "li") and self.in_main:
self.parts.append("\n")
def handle_data(self, data):
if self.in_main:
self.parts.append(data)
parser = MainText()
parser.feed(page)
text = re.sub(r"\n\s*\n+", "\n", "".join(parser.parts)).strip() # drop blank lines
print(text)With BeautifulSoup the same idea is one line: BeautifulSoup(html, "html.parser").find("main").get_text("\n", strip=True). Many sites use <main> or <article> for their content; for others, look at the page's HTML to find the right element.
Keep the metadata
Store these with every document, because you'll need them later:
- Source (file name or URL) and page or section: for citations and for re-indexing.
- Title and headings: they make chunks easier to understand on their own.
- Date or version: to prefer current documents and drop old ones.
- Access information: which users or groups may see it.
Common mistakes
Clean a page of extracted PDF text so the header and page number don't end up inside your chunks.
import re
page = """ACME LTD - EMPLOYEE HANDBOOK
Security
Use a password manager and turn on two-factor login.
Page 12
Never share your password."""
# Remove the header line and any "Page <number>" line, then print what is left
lines = page.split("\n")
print("\n".join(lines))
Text extraction from a PDF returns empty pages. What is the most likely cause?
Summary
- Loading turns files and pages into clean text plus metadata; quality here limits everything after it.
- Use a parser for each format:
pypdffor PDFs, an HTML parser for web pages,python-docxfor Word files. - Clean repeated headers, footers, page numbers, broken words and lines; keep only the main content of web pages.
- Keep source, page, title, date and access as metadata; check samples by eye, and give tables and scans special treatment.
Next: splitting documents into chunks.
Finished reading? Tick it off to track your progress.