Build a Light Document Model

Python で Light Document Model を構築する方法

Pythonでライトドキュメントモデルを構築する方法

ライトドキュメントモデル(LDM)は、Aspose.Words FOSS の Python ネイティブ表現である Word 文書です。本ガイドでは、DOCX ファイルをロードし、DocumentReader とその to_light_document() メソッド(LdmBuilderMixin から)を使用して LDM に変換する方法を示します。


前提条件

要件詳細
Python3.9 以降
Packageaspose-words-foss (MIT ライセンス)
InputA .docx ファイル
pip install aspose-words-foss

Step 1 — DocumentReader をインポート

from aspose.words_foss import DocumentReader

DocumentReader は 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")

次のステップ

参照

 日本語