Python:如何从word文档中删除最后一页? |
您所在的位置:网站首页 › Python中的返回值 › Python:如何从word文档中删除最后一页? |
不幸的是,简单的答案似乎是:你不能用python来做这件事,至少用他们的API是不行的。如果你深入到你的内心,你可能会破解出一些适合你的特定案例的东西。但在过去的10到15分钟的研究中,我做的这似乎是不可能的。 以下是几个问题: python没有页面的概念,请参见Python-docx: identify a page break in paragraph Copying内容从一个文档到另一个文档(或者等效地创建一个空文档并将内容复制到它)是相当复杂的,而且一般不支持python。请参阅combine word document using python docx尽管从(2)中的文章来看,似乎有一个可以帮助的替代包(https://pypi.org/project/docxcompose/)。 编辑:,这是我所得到的。这是相当疯狂的工作,但与一个非常快速的基本测试,虽然我认为它是部分损坏。最后留下了一页空白。这肯定解决不了这个问题,但也许可以成为更多挖掘的起点。 import docx d = docx.Document('test.docx') new_doc = docx.Document() def get_last_page_break(document): paragraph_index = 0 for paragraph in document.paragraphs: paragraph_index += 1 run_index = 0 for run in paragraph.runs: run_index += 1 if 'lastRenderedPageBreak' in run._element.xml: # soft page break lastpara_index = paragraph_index lastrun_index = run_index elif 'w:br' in run._element.xml and 'type="page"' in run._element.xml: # hard page break lastpara_index = paragraph_index lastrun_index = run_index return lastpara_index, lastrun_index def kludgy_remove_last_page(document): new_doc = docx.Document() last_para, lastrun_index = get_last_page_break(d) for para in d.paragraphs[:last_para]: new_para = new_doc.add_paragraph() for run in para.runs[:lastrun_index]: new_para.add_run(run.text) if 'w:br' in run._element.xml and 'type="page"' in run._element.xml: # hard page break new_doc.add_page_break() return new_doc new_doc = kludgy_remove_last_page(d) new_doc.save('removed.docx') |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |