0Pricing
AI Engineering Academy · 课时

文档加载与文本提取

使用 Python 库加载 PDF、Word 文档和纯文本文件,清理提取出的文本,并为分块和嵌入做好准备。

文档加载与文本提取 是 CoddyKit 上的免费 AI Engineering Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Engineering Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Engineering Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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 results

Using 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 docs

Tracking 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 pages

Batch 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, errors

Validating 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 valid

Quick 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.

常见问题解答

「文档加载与文本提取」课时是免费的吗?

是的 — 「文档加载与文本提取」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Engineering Academy 课程的其余内容,请升级到 CoddyKit PRO。 AI Engineering Academy 课程共包含 4 节课。

「文档加载与文本提取」这节课中我会学到什么?

使用 Python 库加载 PDF、Word 文档和纯文本文件,清理提取出的文本,并为分块和嵌入做好准备。 你通过在浏览器中直接运行的动手代码来练习 AI Engineering Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Engineering Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Engineering Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「文档加载与文本提取」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Engineering Academy 课中编写并运行代码吗?

能。每节 AI Engineering Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 文档加载与文本提取
  2. 分块策略:固定大小、按句子与递归
  3. 索引:嵌入并存储分块
  4. 查询、检索与生成
← 返回 AI Engineering Academy