과업 중심으로 정리한 읽기·순회 레시피다. 전부 공개 API만 사용하며, ZIP이나
XML을 직접 열 필요가 없다. 예제의 input.hwpx는 여러분의 문서로 바꿔 쓰면
된다.
Python 블록 판정: 실행 분류 ledger가 이 current manual의 모든 Python 블록을 동결합니다. 이 문서의 블록은 모두 기존 입력 파일(
input.hwpx)이 필요한 조각입니다.
가장 단순한 순회다. document.paragraphs는 본문 문단 리스트를 준다.
from hwpx import HwpxDocument document = HwpxDocument.open("input.hwpx") for paragraph in document.paragraphs: print(paragraph.text)
표 셀·각주 속 문단까지 포함해 "이 문단이 어디에 있는지"가 필요하면
TextExtractor.iter_document_paragraphs()를 쓴다. ParagraphInfo.path는
sec/p[3]/run/tbl/tr[0]/tc[0]/subList/p처럼 문단의 구조 경로를 준다.
from hwpx import TextExtractor extractor = TextExtractor("input.hwpx") for info in extractor.iter_document_paragraphs(include_nested=True): marker = " (중첩)" if info.is_nested else "" print(f"[{info.section.index}:{info.index}] {info.path}{marker}") print(" ", info.text())
extract_text()는 기본으로 각주를 본문 자리에 넣지 않는다(각주 글은 중첩 문단으로 따로 한 줄 나온다).
AnnotationOptions로 동작을 고른다 — "ignore"(기본), "placeholder"(자리표시), "inline"(본문에 삽입).
각주 문단은 중첩 문단으로도 잡히므로, 인라인으로 합칠 때는
include_nested=False로 중복을 피한다.
from hwpx import TextExtractor from hwpx.tools.text_extractor import AnnotationOptions extractor = TextExtractor("input.hwpx") text = extractor.extract_text( include_nested=False, annotations=AnnotationOptions(footnote="inline", endnote="inline"), ) print(text)
각주가 있는 문단은 본문 문단이다[footnote:각주 내용이다]처럼 나온다.
하이라이트·하이퍼링크·컨트롤도 같은 방식의 옵션이 있다(highlight,
hyperlink, control).
구조 검색은 ObjectFinder가 맡는다. 태그로 요소를 찾고, 각 결과의
path·section·text를 읽는다. text는 속성이며, 표처럼 텍스트가
직접 없는 컨테이너 요소에서는 None이다 — 셀 내용은 위의
iter_document_paragraphs() 경로(.../tc[i]/subList/p)로 읽는 편이 쉽다.
from hwpx import ObjectFinder finder = ObjectFinder("input.hwpx") for table in finder.find_all(tag="tbl"): print("표 위치:", table.path, "| 섹션:", table.section.index) cells = finder.find_all(tag="tc") print("셀 수:", len(cells))
굵기·색 같은 서식은 런(run)에 붙는다. 본문 문단의 런을 순회하거나, 특정 서식의 런만 골라낼 수 있다.
from hwpx import HwpxDocument document = HwpxDocument.open("input.hwpx") for run in document.text.iter_runs(): print(repr(run.text), "charPr:", run.char_pr_id_ref) red_runs = document.text.find_runs(text_color="#FF0000") print("빨간 런:", len(red_runs))
table.iter_grid()는 논리 좌표마다 그 자리를 덮는 실제 칸과 병합의 기준 좌표(anchor)·크기(span)를
돌려준다. 병합 칸 하나는 기준 좌표에서 한 번(is_anchor)만 세고, 그 칸의 오른쪽 이웃은
column + col_span 열이다. 라벨 글자로 칸을 찾는 탐색(find_cell_by_label)은 7.0에서
python-hwpx-automation(hwpx_automation.forms)으로 옮겼다.
from hwpx import HwpxDocument document = HwpxDocument.open("input.hwpx") for memo in document.notes.memos: print("메모:", memo.id) for field in document.fields.all: print("누름틀:", field)
문서에 해당 요소가 없으면 빈 컬렉션이 나온다 — 예외가 아니다.
- 편집 호출이 무엇을 돌려주고 어떻게 실패하는지는 {doc}
mutation-semantics - 추출 전용 CLI와 더 많은 패턴은 {doc}
usage - 요소·속성 이름의 의미는 {doc}
schema-overview