有什么办法可以用python计算word文档的页数吗?

问题描述 投票:0回答:1

我被要求计算一个word文档的页数,而不将其转换为pdf类型。

我尝试过“计算节数”方法来计算页数,但事实证明该方法不准确,我需要使用

python-docx
来准确计算word文档的页数 图书馆。

python python-docx
1个回答
0
投票

安装

python-docx library
。你可以这样安装:

pip install python-docx

这是代码:

from docx import Document


def count_pages(doc):
    page_count = 0
    for para in doc.paragraphs:
                 # Microsoft Word 2010 - Level 2 is an text find at the end of the page.
                 # so on the base of it, i count total number of pages. 
        if para.text == 'Microsoft Word 2010 - Level 2':
            page_count += 1
    return page_count


doc_path = 'test.docx'
doc = Document(doc_path)
num_pages = count_pages(doc)

print(f'This document has {num_pages} pages.')

© www.soinside.com 2019 - 2024. All rights reserved.