0Pricing
AI Engineering Academy · 강의

문서 불러오기와 텍스트 추출

Python 라이브러리로 PDF, Word 문서, 일반 텍스트 파일을 불러오고, 추출한 텍스트를 정리해 분할과 임베딩에 사용할 수 있도록 준비합니다.

문서 불러오기와 텍스트 추출은(는) CoddyKit의 무료 AI Engineering Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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.

자주 묻는 질문

“문서 불러오기와 텍스트 추출” 강의는 무료인가요?

네 — “문서 불러오기와 텍스트 추출” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Engineering Academy 강의 전체를 잠금 해제할 수 있습니다. AI Engineering Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“문서 불러오기와 텍스트 추출”에서 뭘 배우나요?

Python 라이브러리로 PDF, Word 문서, 일반 텍스트 파일을 불러오고, 추출한 텍스트를 정리해 분할과 임베딩에 사용할 수 있도록 준비합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Engineering Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

AI Engineering Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 AI Engineering Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“문서 불러오기와 텍스트 추출” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 AI Engineering Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 AI Engineering Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 문서 불러오기와 텍스트 추출
  2. 분할 전략: 고정 크기, 문장 단위, 재귀 방식
  3. 색인: 분할 조각 임베딩 및 저장
  4. 질의, 검색, 생성
← AI Engineering Academy(으)로 돌아가기