小编sar*_*ple的帖子

查找并替换.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
查看次数

Python美丽的汤形式输入解析

我的目标是获取所有输入名称和值的列表.将它们配对并提交表格.名称和值是随机的.

from bs4 import BeautifulSoup # parsing

html = """
<html>
<head id="Head1"><title>Title Page</title></head>
<body>
    <form id="formS" action="login.asp?dx=" method="post">

    <input type=hidden name=qw1NWJOJi/E8IyqHSHA== value='gDcZHY+nV' >
    <input type=hidden name=sfqwWJOJi/E8DFDHSHB== value='kgDcZHY+n' >
    <input type=hidden name=Jsfqw1NdddfDDSDKKSL== value='rNg4pUhnV' >
    </form>

</body>

</html>
"""

html_proc = BeautifulSoup(html)
Run Code Online (Sandbox Code Playgroud)

这个位工作正常:

print html_proc.find("input", value=True)["value"]
> gDcZHY+nV
Run Code Online (Sandbox Code Playgroud)

但是,以下陈述不起作用或不起作用:

print html_proc.find("input", name=True)["name"]
> TypeError: find() got multiple values for keyword argument 'name'

print html_proc.findAll("input", value=True, attrs={'value'})
> []  

print html_proc.findAll('input', value=True)
> <input name="qw1NWJOJi/E8IyqHSHA==" type="hidden" value="gDcZHY+nV">
> <input name="sfqwWJOJi/E8DFDHSHB==" type="hidden" value="kgDcZHY+n"> …
Run Code Online (Sandbox Code Playgroud)

html python parsing beautifulsoup html-parsing

6
推荐指数
2
解决办法
1万
查看次数

标签 统计

python ×2

beautifulsoup ×1

docx ×1

html ×1

html-parsing ×1

parsing ×1

replace ×1

text ×1

zipfile ×1