python docx 替换文字_在docx中进行文本替换,并使用python-docx保存更改的文件

1586010002-jmsa.png

I'm trying to use the python-docx module to replace a word in a file and save the new file with the caveat that the new file must have exactly the same formatting as the old file, but with the word replaced. How am I supposed to do this?

The docx module has a savedocx that takes 7 inputs:

document

coreprops

appprops

contenttypes

websettings

wordrelationships

output

How do I keep everything in my original file the same except for the replaced word?

解决方案

As it seems to be, Docx for Python is not meant to store a full Docx with images, headers, ... , but only contains the inner content of the document. So there's no simple way to do this.

Howewer, here is how you could do it:

First, have a look at the docx tag wiki:

It explains how the docx file can be unzipped: Here's how a typical file looks like:

+--docProps

| + app.xml

| \ core.xml

+ res.log

+--word //this folder contains most of the files that control the content of the document

| + document.xml //Is the actual content of the document

| + endnotes.xml

| + fontTable.xml

| + footer1.xml //Containst the elements in the footer of the document

| + footnotes.xml

| +--media //This folder contains all images embedded in the word

| | \ image1.jpeg

| + settings.xml

| + styles.xml

| + stylesWithEffects.xml

| +--theme

| | \ theme1.xml

| + webSettings.xml

| \--_rels

| \ document.xml.rels //this document tells word where the images are situated

+ [Content_Types].xml

\--_rels

\ .rels

Docx only gets one part of the document, in the method opendocx

def opendocx(file):

'''Open a docx file, return a document XML tree'''

mydoc = zipfile.ZipFile(file)

xmlcontent = mydoc.read('word/document.xml')

document = etree.fromstring(xmlcontent)

return document

It only gets the document.xml file.

What I recommend you to do is:

get the content of the document with **opendocx*

Replace the document.xml with the advReplace method

Open the docx as a zip, and replace the document.xml content's by the new xml content.

Close and output the zipped file (renaming it to output.docx)

If you have node.js installed, be informed that I have worked on DocxGenJS which is templating engine for docx documents, the library is in active development and will be released soon as a node module.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值