pdf의 텍스트 추출

ahncheer·2026년 1월 14일

python

목록 보기
26/26

파이썬으로 hwp, hwpx, docx, pdf의 텍스트 추출 시도

newFile251230 폴더에 hwp, hwpx, docx, pdf 파일 추가

# 251230 test
# pip install python-docx pdfplumber

import os
import subprocess
import shutil
import tempfile
import zipfile
import xml.etree.ElementTree as ET
from docx import Document
import pdfplumber

INPUT = r"\newFile251230"
OUTPUT = r"\newResult251230"

os.makedirs(OUTPUT, exist_ok=True)

# -------------------------------------------------------
# HWP 스트림 디코더 (기존 사용 코드)
# -------------------------------------------------------
def decode_hwp_stream(stream_bytes):
    cleaned = bytearray()
    i = 0
    length = len(stream_bytes)

    while i < length - 3:
        char_bytes = stream_bytes[i:i+2]
        try:
            ch = char_bytes.decode("utf-16-le")
        except:
            i += 4
            continue

        if (
            '\uAC00' <= ch <= '\uD7A3' or
            '0' <= ch <= '9' or
            'A' <= ch <= 'Z' or
            'a' <= ch <= 'z' or
            ch in " .,!?()[]{}:;+-_=*/\n\r\t"
        ):
            cleaned.extend(char_bytes)

        i += 4

    return cleaned.decode("utf-16-le", errors="ignore")

# -------------------------------------------------------
# HWP
# -------------------------------------------------------
def extract_hwp(path):
    temp_dir = tempfile.mkdtemp()
    text = ""

    subprocess.run(
        ["hwp-extract", "--extract-files", "--output-directory", temp_dir, path],
        capture_output=True
    )

    for root, _, files in os.walk(temp_dir):
        for f in files:
            if any(k in f for k in ["PrvText", "BodyText", "Section"]):
                with open(os.path.join(root, f), "rb") as s:
                    text += decode_hwp_stream(s.read()) + "\n"

    shutil.rmtree(temp_dir)
    return text

# -------------------------------------------------------
# HWPX
# -------------------------------------------------------
def extract_hwpx(path):
    text = []
    with zipfile.ZipFile(path) as z:
        for name in z.namelist():
            if name.startswith("Contents/section") and name.endswith(".xml"):
                root = ET.fromstring(z.read(name))
                for elem in root.iter():
                    if elem.text:
                        text.append(elem.text)
    return "\n".join(text)

# -------------------------------------------------------
# DOCX
# -------------------------------------------------------
def extract_docx(path):
    doc = Document(path)
    return "\n".join(p.text for p in doc.paragraphs)

# -------------------------------------------------------
# PDF
# -------------------------------------------------------
def extract_pdf(path):
    text = []
    with pdfplumber.open(path) as pdf:
        for page in pdf.pages:
            text.append(page.extract_text() or "")
    return "\n".join(text)

# -------------------------------------------------------
# 메인 처리
# -------------------------------------------------------
for fname in os.listdir(INPUT):
    fpath = os.path.join(INPUT, fname)
    lower = fname.lower()

    print(f"\n📄 처리 중: {fname}")

    try:
        if lower.endswith(".hwp"):
            content = extract_hwp(fpath)
        elif lower.endswith(".hwpx"):
            content = extract_hwpx(fpath)
        elif lower.endswith(".docx") or lower.endswith(".doc"):
            content = extract_docx(fpath)
        elif lower.endswith(".pdf"):
            content = extract_pdf(fpath)
        else:
            print("⏭️ 지원하지 않는 형식, 건너뜀")
            continue

        out_path = os.path.join(OUTPUT, fname + "_TEXT.txt")
        with open(out_path, "w", encoding="utf-8") as out:
            out.write(content)

        print(f"✅ 완료 → {out_path}")

    except Exception as e:
        print(f"❌ 실패: {fname} / {e}")

print("\n🎉 모든 문서 일괄 텍스트 추출 완료!")

hwpx파일은 일부만, pdf 파일은 대부분의 텍스트 추출이 가능한 것을 확인할 수 있다

251204기준 한글 파일을 읽을 수 있는 오픈소스가 있는지

※ hwp 파일 지원 여부
- :o:가능 : Gemini
- :x:불가능 : ChatGPT, perplexity, Claude
※ .hwp 파일
- Window 환경에서 파이썬 코드로 읽는 것은 어려움
- “완전한 텍스트”를 바로 얻기보다는, 객체·메타데이터를 뽑고 추가 파싱이 필요
※ .hwpx (다른 한글파일)
- hwp-extract을 사용해 텍스트 추출 가능
(https://github.com/volexity/hwp-extract)
- pyhw가 가능하지만, 유지보수가 중단됨
profile
개인 공부 기록용.

0개의 댓글