首页 > 解决方案 > 如何打开/保存要编辑为xml的docx文件,并在使用python编辑后将结果另存为docx

问题描述

我有一个docx文件,我需要在其中编辑其段落(段落可能包含方程式)。我尝试使用这些工作来完成这些工作,python-docx但没有成功,因为编辑每个段落的文本并用编辑后的新段落替换它需要调用p.add_paragraphs(editText(paragraph.text))忽略并省略任何数学方程的调用。

通过寻找一种方法来实现这个目标,我发现这项工作可以通过 XML 代码找到<w:t>标签并编辑它们的内容,如下所示:

tree= ET.parse(filename)
root=tree.getroot()

for par in root.findall('w:p'):
   if par.find('w:r'):
   myText= par.find('w:r').find('w:t')
   myText.text= editText(myText.text)

然后我必须将结果保存为 docx。我的问题是:文件名的格式是什么?它应该是一个 document.xml 文件吗?如果是这样,我怎样才能从我的原始 document.docx 文件中获得它?还有一个问题是如何将结果再次保存为 .docx 文件?

为了将 docx 保存为 xml,我尝试将其保存为document.save('Document2.xml')。但结果的内容不正确。

你能给我一些建议吗?

标签: pythonxmldocx

解决方案


完全没有这方面的经验,但也许这就是你想要的? https://virantha.com/2013/08/16/reading-and-writing-microsoft-word-docx-files-with-python/ 来自文章:

import zipfile
from lxml import etree
class DocsWriter:
    def __init__(self, docx_file):
        self.zipfile = zipfile.ZipFile(docx_file)


    def _write_and_close_docx (self, xml_content, output_filename):
        """ Create a temp directory, expand the original docx zip.
            Write the modified xml to word/document.xml
            Zip it up as the new docx
        """

        tmp_dir = tempfile.mkdtemp()

        self.zipfile.extractall(tmp_dir)

        with open(os.path.join(tmp_dir,'word/document.xml'), 'w') as f:
            xmlstr = etree.tostring (xml_content, pretty_print=True)
            f.write(xmlstr)

        # Get a list of all the files in the original docx zipfile
        filenames = self.zipfile.namelist()
        # Now, create the new zip file and add all the filex into the archive
        zip_copy_filename = output_filename
        with zipfile.ZipFile(zip_copy_filename, "w") as docx:
            for filename in filenames:
                docx.write(os.path.join(tmp_dir,filename), filename)

        # Clean up the temp dir
        shutil.rmtree(tmp_dir)

据我所知,此代码块将xml文档编写为.docx. 有关更多上下文,请参阅文章。


推荐阅读