def getstr(str1):
tmp3=[“NULL”,”NULL”]
if str1.find(“,”)!=-1:
tmpa=str1.split(“,”)
if len(tmpa)==2:
if tmpa[0].find(“:”)!=-1:
tmpb=tmpa[0].split(“:”)
tmp3[0]=tmpb[1]
if tmpa[1].find(“:”)!=-1:
tmpb=tmpa[1].split(“:”)
tmp3[1]=tmpb[1]
if len(tmpa)==3:
if tmpa[0].find(“:”)!=-1:
tmpb=tmpa[0].split(“:”)
tmp3[0]=tmpb[1]
if tmpa[2].find(“:”)!=-1:
tmpb=tmpa[2].split(“:”)
tmp3[1]=tmpb[1]
tmp3[1]=tmp3[1].replace(‘\n}’,””)
return tmp3
idlist=[12017,12018,12019,12020,12021,12022,12023,12024,12025,12026,12027,12028,12029,12030,12031,12032,12033,12034,12035,12036,12037,12038,12039,12040,12041,12042,12043,12044,12045,12046,12047,12048,12049,12050,12051,12052,12053,12054,12055,12056,12057,12058,12059,12060,12061,12062,12063,12064,12065,12066,12067,12068,12069,12070,12071]
newcontent=””
f=open(‘dj.txt’,”r”,encoding=’utf-8’)
line=f.readline()
while line:
tmpa=line.replace(“NULL”,”‘NULL’”).split(“‘, ‘“)
tmp1=getstr(tmpa[13])
for number1 in idlist:
if tmp1[0]==’NULL’:
break
if int(tmp1[0])==number1:
tmpss=”,”+tmp1[0]+”,”+tmp1[1]+”);”
newline=line.replace(“opt_type)”,”opt_type,newid,commentnum)”)
newline=newline.replace(“);”,tmpss)
newcontent=newcontent+newline
break
line=f.readline()
f.close()
f1=open(‘ndj.txt’,”w”,encoding=’utf-8’)
f1.write(newcontent)
f1.close()
以下是通过Python-docx修改WORD文档,lxml xpath访问WORD的docx文档。
#查找numbering.xml中的序号定义
body_xml_str=doc.part.numbering_part._element.xml
from lxml import etree
body_xml=etree.fromstring(body_xml_str)
Namespaces={‘w’:’http://schemas.openxmlformats.org/wordprocessingml/2006/main’}
xps=”.//w:num[@w:numId=’”+str(numid)+”‘]/w:abstractNumId/@w:val”
abstractNumid=body_xml.xpath(xps, namespaces=Namespaces)
tstr=”.//w:abstractNum[@w:abstractNumId=’”+str(abstractNumid[0])+”‘]/w:lvl[@w:ilvl=”+str(ilvl)+”]/w:numFmt”
print(tstr)
tnode=body_xml.xpath(tstr, namespaces=Namespaces)
#tnode[0].attrib[‘val’]=”lowerRoman”
tnode[0].set(qn(‘w:val’),’lowerRoman’ )
print(tnode)
删除节点:
from docx.oxml.xmlchemy import OxmlElement
testppr=para._element.getchildren()[1]
print(showxml(testppr.xml))
for elem in testppr:
for st in elem:
print(“st=”, st.tag)
if st.tag==”{http://schemas.openxmlformats.org/wordprocessingml/2006/main}rFonts”:
print(“remove ok”)
elem.remove(st)
print(“new=”, showxml(testppr.xml))
添加节点属性
from docx.oxml.xmlchemy import OxmlElement
testppr=para._element.getchildren()[1]
print(showxml(testppr.xml))
for elem in testppr:
for st in elem:
#print(“st=”, st.attrib)
if st.tag==”{http://schemas.openxmlformats.org/wordprocessingml/2006/main}rFonts”:
print(“remove ok”)
#elem.remove(st)
st.attrib[‘eastAsia’]=”方正小标宋简体”
