python - 如何打开/保存要编辑为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'
)。但结果的内容不正确。
你能给我一些建议吗?
解决方案
完全没有这方面的经验,但也许这就是你想要的? 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
. 有关更多上下文,请参阅文章。
推荐阅读
- python - 在按顺序排序并在一个范围内随机抽取的系列中创建一个唯一的元组列表
- kubernetes - 如何通过 nodejs 库重启 kubernetes 部署
- python - 如何根据条件将值附加到 Pandas 数据框中的单个单元格中的列表
- java - Hibernate从2个表中创建一个整数类型列表
- python - 已安装 mpi4py 但 Python IDLE 无法导入 mpi4py.MPI
- oracle - 运行 oracle oracle apex 20.1 应用程序时出现以下错误:禁止请求的操作不允许
- javascript - Javascript:在任何地方禁用双击
- css - 自定义列引导的宽度
- laravel - 加载资源失败:服务器响应状态为 500 () laravel cpanel
- r - 创建 R 函数时找不到对象