我一直在寻找一种方法来查找和替换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行缺少右括号')'
我需要帮助替换word文档中的字符串,同时保持整个文档的格式.
我正在使用python-docx,在阅读文档之后,它适用于整个段落,所以我放松了格式,如粗体或斜体字.包括要替换的文本是粗体,我想保持这种方式.我正在使用此代码:
from docx import Document
def replace_string2(filename):
doc = Document(filename)
for p in doc.paragraphs:
if 'Text to find and replace' in p.text:
print 'SEARCH FOUND!!'
text = p.text.replace('Text to find and replace', 'new text')
style = p.style
p.text = text
p.style = style
# doc.save(filename)
doc.save('test.docx')
return 1
Run Code Online (Sandbox Code Playgroud)
因此,如果我实现它并想要类似的东西(包含要替换的字符串的段落丢失其格式):
这是第1段,这是一个粗体文本.
这是第2段,我将替换旧文本
目前的结果是:
这是第1段,这是一个粗体文本.
这是第2段,我将替换新的文本