Làm thế nào để tạo một mô hình tài liệu ánh sáng trong Python
Làm thế nào để tạo một mô hình tài liệu ánh sáng trong Python
Mô hình tài liệu ánh sáng (LDM) là sự đại diện của FOSS về Python. tài liệu Word. hướng dẫn này cho thấy cách tải một tập tin DOCX và chuyển đổi nó thành một LDM sử dụng DocumentReader Và nó to_light_document() Phương pháp từ LdmBuilderMixin.
Prerequisites
| Requirement | Detail |
|---|---|
| Python | 3.9 or later |
| Package | aspose-words-foss (Một giấy phép) |
| Input | A .docx file |
pip install aspose-words-fossBước 1 - Import DocumentReader
from aspose.words_foss import DocumentReaderDocumentReader thừa kế từ LdmBuilderMixin, mà cung cấp cho to_light_document() Phương pháp .
Bước 2 - Tải file DOCX
Sử dụng load_file() cho một file path, load_stream() Đối với một tài liệu tương tự đối tượng, hoặc load_bytes() Đối với các byte:
reader = DocumentReader()
reader.load_file("data/my_document.docx")Bước 3 - Xây dựng LDM
Call to_light_document() để chuyển đổi DOCX tải thành LDM Document:
doc = reader.to_light_document()
print("Page count:", doc.page_count)
print("Sections:", len(doc.sections))
print("Paragraphs:", len(doc.all_paragraphs))Bước 4 - Kiểm tra tài liệu
LDM Document Hiển thị toàn bộ cây tài liệu. điểm nhập chung:
# 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)Bước 5 - Viết lại với DOCX (tùy chọn)
Sau khi kiểm tra hoặc sửa đổi LDM, sử dụng LdmDocxWriter Để tạo file DOCX:
from aspose.words_foss import LdmDocxWriter
writer = LdmDocxWriter()
writer.write(doc, "output/result.docx")Bước tiếp theo
- Tạo file DOCX với LdmDocxWriter - Đóng đầy đủ API
- Làm việc với các phần tài liệu - Navigate Sections and Paragraphs (các phần và đoạn)