tlewis 的代码用于从 docx 中查找特定文本并替换它。在您的情况下,还有其他事情要做:检测新行,并查看它们是否连续超过两条新行。换句话说,换行符只是一个段落(<w:p>
标签),里面没有任何文字。
我添加了一些评论,向您展示如何使用 zip。
import zipfile #Import the zip Module
from lxml import etree #Useful to transform string into xml, and xml into string
templateDocx = zipfile.ZipFile("C:/Template.docx") #Here is the path to the file you want to import
newDocx = zipfile.ZipFile("C:/NewDocument.docx", "a") #This is the name of the outputed file
#Open the document.xml file, the file that contains the content
with open(templateDocx.extract("word/document.xml", "C:/") as tempXmlFile:
tempXmlStr = tempXmlFile.read()
tempXmlXml= etree.fromstring(tempXmlStr) #Convert the string into XML
############
# Algorithm detailled at the bottom,
# You have to write here the code to select all <w:p> tags, look if there is a <w:t> tag.
############
tempXmlStr = etree.tostring(tempXmlXml, pretty_print=True) # Convert the changed XML into a string
with open("C:/temp.xml", "w+") as tempXmlFile:
tempXmlFile.write(tempXmlStr) #Write the changed file
for file in templateDocx.filelist:
if not file.filename == "word/document.xml":
newDocx.writestr(file.filename, templateDocx.read(file)) #write all files except the changed ones in the zipArchive
newDocx.write("C:/temp.xml", "word/document.xml") #write the document.xml file
templateDocx.close() #Close both template And new Docx
newDocx.close() # Close
如何编写算法以删除多个新行
这是我创建的示例文档:
下面是document.xml的对应代码:
<w:p w:rsidR="006C517B" w:rsidRDefault="00761A87">
<w:bookmarkStart w:id="0" w:name="_GoBack" />
<w:bookmarkEnd w:id="0" />
<w:r>
<w:t>First Line</w:t>
</w:r>
</w:p>
<w:p w:rsidR="00761A87" w:rsidRDefault="00761A87" />
<w:p w:rsidR="00761A87" w:rsidRDefault="00761A87">
<w:proofErr w:type="spellStart" />
<w:r>
<w:t>Third</w:t>
</w:r>
<w:proofErr w:type="spellEnd" />
<w:r>
<w:t xml:space="preserve"> Line</w:t>
</w:r>
</w:p>
<w:p w:rsidR="00761A87" w:rsidRDefault="00761A87" />
<w:p w:rsidR="00761A87" w:rsidRDefault="00761A87" />
<w:p w:rsidR="00761A87" w:rsidRDefault="00761A87">
<w:r>
<w:t>Six Line</w:t>
</w:r>
</w:p>
<w:p w:rsidR="00761A87" w:rsidRDefault="00761A87" />
<w:p w:rsidR="00761A87" w:rsidRDefault="00761A87" />
<w:p w:rsidR="00761A87" w:rsidRDefault="00761A87" />
<w:p w:rsidR="00761A87" w:rsidRDefault="00761A87">
<w:proofErr w:type="spellStart" />
<w:r>
<w:t>Ten</w:t>
</w:r>
<w:proofErr w:type="spellEnd" />
<w:r>
<w:t xml:space="preserve"> Line</w:t>
</w:r>
</w:p>
<w:p w:rsidR="00761A87" w:rsidRDefault="00761A87">
<w:proofErr w:type="spellStart" />
<w:r>
<w:t>Eleven</w:t>
</w:r>
<w:proofErr w:type="spellEnd" />
<w:r>
<w:t xml:space="preserve"> Line</w:t>
</w:r>
</w:p>
如您所见,新行是空的<w:p>
,如下所示:
<w:p w:rsidR="00761A87" w:rsidRDefault="00761A87" />
要删除多个新行,请检查它们是否为多个 empty <w:p>
,并删除除第一行之外的所有行。
希望有帮助!