Python で Light Document Model を構築する方法
Pythonでライトドキュメントモデルを構築する方法
ライトドキュメントモデル(LDM)は、Aspose.Words FOSS の Python ネイティブ表現である Word 文書です。本ガイドでは、DOCX ファイルをロードし、DocumentReader とその to_light_document() メソッド(LdmBuilderMixin から)を使用して LDM に変換する方法を示します。
前提条件
| 要件 | 詳細 |
|---|---|
| Python | 3.9 以降 |
| Package | aspose-words-foss (MIT ライセンス) |
| Input | A .docx ファイル |
pip install aspose-words-fossStep 1 — DocumentReader をインポート
from aspose.words_foss import DocumentReaderDocumentReader は LdmBuilderMixin を継承し、to_light_document() メソッドを提供します。
Step 2 — DOCX ファイルをロード
ファイルパスには load_file()、ファイルライクオブジェクトには load_stream()、または生のバイトには load_bytes() を使用してください:
reader = DocumentReader()
reader.load_file("data/my_document.docx")ステップ 3 — LDM を構築する
ロードした DOCX を LDM Document に変換するには、to_light_document() を呼び出します:
doc = reader.to_light_document()
print("Page count:", doc.page_count)
print("Sections:", len(doc.sections))
print("Paragraphs:", len(doc.all_paragraphs))ステップ 4 — ドキュメントを検査する
LDM Document は完全なドキュメントツリーを公開します。一般的なエントリーポイント:
# Read full text
print(doc.text[:300])
# Iterate sections
for section in doc.sections:
print("Section paragraphs:", len(section.paragraphs))
# Find headings (up to H2)
for heading in doc.headings(max_level=2):
print("Heading:", heading.text)ステップ 5 — DOCX に書き戻す(オプション)
LDM を検査または変更した後、LdmDocxWriter を使用して DOCX ファイルを生成します:
from aspose.words_foss import LdmDocxWriter
writer = LdmDocxWriter()
writer.write(doc, "output/result.docx")次のステップ
- LdmDocxWriter を使用した DOCX ファイルの書き込み — フル書き込み API
- ドキュメント セクションの操作 — セクションと段落をナビゲートする