我被要求计算一个word文档的页数,而不将其转换为pdf类型。
我尝试过“计算节数”方法来计算页数,但事实证明该方法不准确,我需要使用
python-docx
来准确计算word文档的页数
图书馆。
安装
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.')