小编cvd*_*len的帖子

查找并替换.docx文件中的文本 - Python

我一直在寻找一种方法来查找和替换docx文件中的文本而运气不佳.我已经尝试过docx模块而无法使用它.最后,我使用zipfile模块计算了下面描述的方法,并替换了docx存档中的document.xml文件.为此,您需要一个模板文档(docx),其中您要替换的文本作为唯一字符串,无法与文档中的任何其他现有或未来文本匹配(例如,"XXXMEETDATEXXX上与XXXCLIENTNAMEXXX的会议进行得非常顺利. ").

import zipfile

replaceText = {"XXXCLIENTNAMEXXX" : "Joe Bob", "XXXMEETDATEXXX" : "May 31, 2013"}
templateDocx = zipfile.ZipFile("C:/Template.docx")
newDocx = zipfile.ZipFile("C:/NewDocument.docx", "a")

with open(templateDocx.extract("word/document.xml", "C:/")) as tempXmlFile:
    tempXmlStr = tempXmlFile.read()

for key in replaceText.keys():
    tempXmlStr = tempXmlStr.replace(str(key), str(replaceText.get(key)))

with open("C:/temp.xml", "w+") as tempXmlFile:
    tempXmlFile.write(tempXmlStr)

for file in templateDocx.filelist:
    if not file.filename == "word/document.xml":
        newDocx.writestr(file.filename, templateDocx.read(file))

newDocx.write("C:/temp.xml", "word/document.xml")

templateDocx.close()
newDocx.close()
Run Code Online (Sandbox Code Playgroud)

我的问题是这种方法有什么问题?我对这些东西很陌生,所以我觉得别人应该已经弄明白了.这让我相信这种方法存在一些问题.但它的确有效!我在这里错过了什么?

.

以下是我想要学习这些东西的其他人的思考过程的演练:

步骤1)准备要作为键替换的文本字符串的Python字典和作为项目的新文本(例如{"XXXCLIENTNAMEXXX":"Joe Bob","XXXMEETDATEXXX":"2013年5月31日"}).

步骤2)使用zipfile模块打开模板docx文件.

步骤3)使用追加访问模式打开一个新的docx文件.

步骤4)从模板docx文件中提取document.xml(所有文本都存在),并将xml读取为文本字符串变量.

步骤5)使用for循环将xml文本字符串中字典中定义的所有文本替换为新文本.

步骤6)将xml文本字符串写入新的临时xml文件.

步骤7)使用for循环和zipfile模块将模板docx存档中的所有文件复制到新的docx存档除了word/document.xml文件.

步骤8)将带有替换文本的临时xml文件写入新的docx存档作为新的word/document.xml文件.

步骤9)关闭模板和新的docx存档.

步骤10)打开新的docx文档,享受替换后的文本!

- 编辑 - 第7行和第11行缺少右括号')'

python text replace docx zipfile

11
推荐指数
1
解决办法
8125
查看次数

标签 统计

docx ×1

python ×1

replace ×1

text ×1

zipfile ×1