Build a Light Document Model

在Python中如何构建轻文档模型?

在Python中如何构建轻文档模型?

轻文档模型 (LDM) 是Aspose.Words 的 Python 原生表示. 这份指南说明如何加载DOCX文件并将其转换为一个 Word文档. 使用LDM的方法 DocumentReader 及其 to_light_document() 方法从 LdmBuilderMixin.


Prerequisites

RequirementDetail
Python3.9 or later
Packageaspose-words-foss (MIT授权)
Input其他 .docx 文件
pip install aspose-words-foss

步骤1 导入文档阅读器

from aspose.words_foss import DocumentReader

DocumentReader 继承的 LdmBuilderMixin,提供了新的技术. to_light_document() 方法.


步骤2 加载DOCX文件

使用情况 load_file() 对于文件路径, load_stream() 对于文件类对象,或 load_bytes() 对于原始字节:

reader = DocumentReader()
reader.load_file("data/my_document.docx")

步骤3 构建LDM

Call to_light_document() 将加载的DOCX转换为LDM. Document:

doc = reader.to_light_document()
print("Page count:", doc.page_count)
print("Sections:", len(doc.sections))
print("Paragraphs:", len(doc.all_paragraphs))

步骤4 检查文件

部署 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 (可选)

在检查或修改后,使用: LdmDocxWriter 制作一个DOCX文件:

from aspose.words_foss import LdmDocxWriter

writer = LdmDocxWriter()
writer.write(doc, "output/result.docx")

接下来的步骤

See Also

 中文