Carregamento de documentos e extração de texto
Carregue PDFs, documentos do Word e arquivos de texto simples usando bibliotecas Python, limpe o texto extraído e prepare-o para divisão em partes e geração de embeddings.
Carregamento de documentos e extração de texto é uma aula grátis de AI Engineering Academy no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de AI Engineering Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de AI Engineering Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Why Document Loading Is Non-Trivial
The first stage of any RAG pipeline is getting raw text out of your documents. This sounds simple but is surprisingly tricky in practice. PDF files may embed text as characters, as images, or as a mix of both. Word documents contain formatting markup you must strip. HTML pages include navigation menus and ads alongside the real content. A robust loader must handle all these cases and produce clean, coherent text for chunking.
Loading PDFs with pypdf
pypdf is the standard Python library for reading PDF files that contain embedded text. It extracts text page by page, preserving the original page boundaries which are valuable metadata. However, pypdf cannot read scanned PDFs (images of text) — those require OCR. Always extract page numbers alongside text so you can cite the exact page in your RAG citations.
from pypdf import PdfReader
def load_pdf(file_path):
reader = PdfReader(file_path)
pages = []
for page_num, page in enumerate(reader.pages, start=1):
text = page.extract_text()
if text and text.strip(): # skip blank pages
pages.append({
'text': text,
'metadata': {
'source': file_path,
'page': page_num,
'doc_type': 'pdf'
}
})
return pages
docs = load_pdf('annual_report.pdf')
print(f'Loaded {len(docs)} non-empty pages')Loading Word Documents with python-docx
Microsoft Word files (.docx) store content in XML format. The python-docx library parses this XML and exposes paragraphs, tables, and headings as Python objects. Extract paragraph text sequentially and capture heading levels to preserve document structure — section headings are valuable context that improves chunking and retrieval quality when included with the text they introduce.
from docx import Document
def load_docx(file_path):
doc = Document(file_path)
sections = []
current_section = {'heading': '', 'text': ''}
for para in doc.paragraphs:
if para.style.name.startswith('Heading'):
if current_section['text'].strip():
sections.append(current_section.copy())
current_section = {'heading': para.text, 'text': ''}
else:
current_section['text'] += para.text + '\n'
if current_section['text'].strip():
sections.append(current_section)
return [{'text': f"{s['heading']}\n{s['text']}",
'metadata': {'source': file_path, 'section': s['heading']}}
for s in sections]Loading Web Pages and HTML
HTML pages contain a lot of noise: navigation bars, footers, cookie banners, and advertisement blocks. Use BeautifulSoup to parse the HTML and extract only the main content area. Target elements like <article>, <main>, or content-specific CSS classes. Remove script, style, and nav tags before extracting text to avoid polluting your chunks with JavaScript code or menu items.
import requests
from bs4 import BeautifulSoup
def load_url(url):
response = requests.get(url, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# Remove noise elements
for tag in soup(['script', 'style', 'nav', 'footer', 'header', 'aside']):
tag.decompose()
# Try to find main content
main = soup.find('article') or soup.find('main') or soup.find('body')
text = main.get_text(separator='\n', strip=True)
return [{'text': text, 'metadata': {'source': url, 'doc_type': 'html'}}]Handling Scanned PDFs with OCR
Scanned PDFs store pages as images with no embedded text. To extract text you need Optical Character Recognition (OCR). The pytesseract library wraps Google's Tesseract OCR engine. OCR is slower and less accurate than text extraction (80-95% character accuracy on good scans), so always prefer digital PDFs when available. Signal when OCR was used in the metadata so you can review low-confidence extractions.
import pytesseract
from pdf2image import convert_from_path
def load_scanned_pdf(file_path):
# Convert PDF pages to PIL images
pages_as_images = convert_from_path(file_path, dpi=300)
results = []
for page_num, img in enumerate(pages_as_images, start=1):
text = pytesseract.image_to_string(img, lang='eng')
results.append({
'text': text,
'metadata': {
'source': file_path,
'page': page_num,
'ocr': True # flag for quality review
}
})
return resultsUsing Unstructured for Any Format
The unstructured library is a Swiss army knife for document loading that handles PDFs, Word, Excel, PowerPoint, HTML, emails, and more with a unified API. It uses heuristics to identify document elements (title, narrative text, table, header) and returns them as structured objects. This is especially useful when your corpus contains mixed document types and you want element-level metadata without writing format-specific parsers.
from unstructured.partition.auto import partition
def load_any_document(file_path):
elements = partition(filename=file_path)
docs = []
for element in elements:
docs.append({
'text': str(element),
'metadata': {
'source': file_path,
'element_type': type(element).__name__,
'category': element.category
}
})
return docs
# Works on .pdf, .docx, .pptx, .html, .eml, .xlsx
docs = load_any_document('presentation.pptx')Text Cleaning After Extraction
Raw extracted text is rarely clean. PDF extraction often produces hyphenated line breaks from column layouts, extra whitespace, page headers repeated on every page, and garbled special characters. Apply a cleaning pipeline: remove excessive whitespace, rejoin hyphenated words across line breaks, strip page headers and footers identified by pattern matching, and normalize Unicode characters. Clean text leads to dramatically better chunk coherence.
import re
def clean_text(text):
# Rejoin hyphenated line breaks (PDF column artifacts)
text = re.sub(r'-(\n)([a-z])', r'\2', text)
# Normalize whitespace
text = re.sub(r' +', ' ', text)
text = re.sub(r'\n{3,}', '\n\n', text)
# Remove page numbers standing alone on a line
text = re.sub(r'^\d+$', '', text, flags=re.MULTILINE)
# Strip leading/trailing whitespace from each line
lines = [line.strip() for line in text.split('\n')]
return '\n'.join(lines).strip()Loading from Databases and APIs
Not all knowledge lives in files. Internal databases, CRM systems, ticketing tools, and REST APIs are also sources. Load structured database rows by joining relevant tables and concatenating field values into natural-language paragraphs that the embedding model can understand. For APIs, fetch paginated results and serialize each record as a text document with key-value pairs.
import psycopg2
def load_from_database(conn_string, query):
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
cursor.execute(query)
columns = [desc[0] for desc in cursor.description]
docs = []
for row in cursor.fetchall():
# Convert row to natural language text
parts = [f'{col}: {val}' for col, val in zip(columns, row) if val]
text = '\n'.join(parts)
docs.append({'text': text, 'metadata': {'source': 'database'}})
conn.close()
return docsTracking Document Provenance
Every loaded document should carry provenance metadata throughout the entire pipeline: source URL or file path, document title, author, creation date, and last modified date. This metadata travels with each chunk into the vector store and surfaces in LLM citations. Without provenance, you cannot tell users where an answer came from, you cannot update specific documents in the index, and you cannot filter retrieval by source attributes.
import os
from datetime import datetime
def load_pdf_with_provenance(file_path):
from pypdf import PdfReader
reader = PdfReader(file_path)
stat = os.stat(file_path)
base_metadata = {
'source': file_path,
'title': reader.metadata.get('/Title', os.path.basename(file_path)),
'author': reader.metadata.get('/Author', 'Unknown'),
'doc_type': 'pdf',
'file_size_kb': stat.st_size // 1024,
'loaded_at': datetime.utcnow().isoformat()
}
pages = []
for i, page in enumerate(reader.pages, 1):
text = page.extract_text()
if text and text.strip():
pages.append({'text': text, 'metadata': {**base_metadata, 'page': i}})
return pagesBatch Loading Large Document Collections
When indexing thousands of documents, load them in parallel using concurrent.futures to saturate I/O and CPU resources. Implement a progress tracker and error log so failed document loads do not silently drop content from your index. Never let a single corrupt file crash the entire loading job — catch exceptions per document and continue to the next one.
from concurrent.futures import ThreadPoolExecutor, as_completed
def batch_load_documents(file_paths, max_workers=8):
all_docs = []
errors = []
with ThreadPoolExecutor(max_workers=max_workers) as executor:
future_to_path = {
executor.submit(load_pdf_with_provenance, p): p
for p in file_paths
}
for future in as_completed(future_to_path):
path = future_to_path[future]
try:
docs = future.result()
all_docs.extend(docs)
print(f'Loaded {len(docs)} pages from {path}')
except Exception as e:
errors.append({'path': path, 'error': str(e)})
return all_docs, errorsValidating Loaded Content Quality
After loading, validate that you extracted meaningful content. Check for: minimum text length (skip chunks with fewer than 50 characters), language detection (if your RAG is English-only, filter non-English pages), and garbled text detection (high ratio of non-ASCII characters may indicate OCR failure or encoding issues). Log statistics like pages loaded, average page length, and error rate to catch loading problems early.
def validate_documents(docs, min_length=100):
valid = []
skipped = 0
for doc in docs:
text = doc['text']
if len(text) < min_length:
skipped += 1
continue
# Check for high non-ASCII ratio (garbled OCR)
non_ascii = sum(1 for c in text if ord(c) > 127)
if non_ascii / max(len(text), 1) > 0.3:
skipped += 1
continue
valid.append(doc)
print(f'Valid: {len(valid)}, Skipped: {skipped}')
return validQuick Check
Test your understanding of AI Engineering concepts from this lesson.
Lesson Recap
In this lesson you learned: format-specific loaders for PDFs with pypdf, Word documents with python-docx, HTML with BeautifulSoup, and scanned documents with OCR, the unstructured library as a unified multi-format loader, and production best practices including text cleaning, provenance metadata, batch parallel loading, and content validation. Next up we tackle chunking strategies that determine how retrieved text maps to model context.
Perguntas Frequentes
A aula “Carregamento de documentos e extração de texto” é grátis?
Sim — o texto completo de “Carregamento de documentos e extração de texto” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de AI Engineering Academy, atualize para CoddyKit PRO. O curso de AI Engineering Academy inclui 4 aulas no total.
O que vou aprender em “Carregamento de documentos e extração de texto”?
Carregue PDFs, documentos do Word e arquivos de texto simples usando bibliotecas Python, limpe o texto extraído e prepare-o para divisão em partes e geração de embeddings. Você pratica AI Engineering Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar AI Engineering Academy?
Nenhuma experiência prévia é necessária. AI Engineering Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.
Quanto tempo leva a aula “Carregamento de documentos e extração de texto”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de AI Engineering Academy?
Sim. Cada aula de AI Engineering Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Carregamento de documentos e extração de texto
- Estratégias de divisão: fixa, por sentença e recursiva
- Indexação: gerando embeddings e armazenando partes
- Consultar, recuperar e gerar