国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python處理XML格式數(shù)據(jù)的方法詳解

2020-02-23 04:28:35
字體:
供稿:網(wǎng)友

本文實例講述了Python處理XML格式數(shù)據(jù)的方法。分享給大家供大家參考,具體如下:

這里的操作是基于Python3平臺。

在使用Python處理XML的問題上,首先遇到的是編碼問題。

Python并不支持gb2312,所以面對encoding="gb2312"的XML文件會出現(xiàn)錯誤。Python讀取的文件本身的編碼也可能導(dǎo)致拋出異常,這種情況下打開文件的時候就需要指定編碼。此外就是XML中節(jié)點所包含的中文。

我這里呢,處理就比較簡單了,只需要修改XML的encoding頭部。

#!/usr/bin/env pythonimport os, sysimport redef replaceXmlEncoding(filepath, oldEncoding='gb2312', newEncoding='utf-8'):  f = open(filepath, mode='r')  content = f.read()  content = re.sub(oldEncoding, newEncoding, content)  f.close()  f = open(filepath, mode='w')  f.write(content)  f.close()if __name__ == "__main__":  replaceXmlEncoding('./ActivateAccount.xml')

接著是使用xml.etree.ElementTree來操作XML文件。

在一個類里面定義__call__函數(shù)可以使得該類可調(diào)用,比如下面代碼的最后幾行,在__main__函數(shù)中。這也很突出地體現(xiàn)了在Python的世界里,一切都是對象,包括對象本身 :)

一直覺得__main__函數(shù)用來測試真是蠻好用的。

#!/usr/bin/env pythonimport os, reimport xml.etree.ElementTree as etreeLocale_Path = "./locale.txt"class xmlExtractor(object):  def __init__(self):    pass  def __call__(self, filepath):    retDict = {}    f = open(filepath, 'r')    Line = len(open(filepath, 'r').readlines())    retDict['Line'] = Line    tree = etree.parse(f)    root = tree.find("ResItem")    Id = root.get("ID")    retDict['Title'] = Id    resItemCnt = len(list(root.findall("ResItem"))) + 1    retDict['ResItemCount'] = resItemCnt    retDict['ChineseTip'] = 'None'    for child in root:      attrDict = child.attrib      keyword = "Name"      if(keyword in attrDict.keys() and attrDict['Name'] == "Caption"):        if len(child.attrib['Value']) > 1:          if child.attrib['Value'][0] == '~':            title = child.attrib['Value'][1:]          else:            title = child.attrib['Value'][0:]          #print(title)          chs = open(Locale_Path).read()          pattern = '<String id="' + title + '">[^>]+>'          m = re.search(pattern, chs)          if m != None:            realTitle = re.sub('<[^>]+>', '', m.group(0))            retDict['ChineseTip'] = realTitle    f.close()    return retDictif __name__ == "__main__":  fo = xmlExtractor()  d = fo('./ActivateAccount.xml')  print(d)

最后,就是入口文件,導(dǎo)入上面兩個文件,使用xml.dom和os.listdir來遞歸處理XML文件,并生成一個結(jié)果集。

一直覺得Python的UnboundLocalError錯誤挺有意思的,不知道是不是符號表的覆蓋問題。

#!/usr/bin/env pythonfrom xmlExtractor import *from replaceXmlEncoding import *from xml.dom import minidom,Nodedoc = minidom.Document()extractor = xmlExtractor()totalLines = 0totalResItemCnt = 0totalXmlFileCnt = 0totalErrorCnt = 0errorFileList = []xmlRoot = doc.createElement("XmlResourceFile")doc.appendChild(xmlRoot)def myWalkDir(level, path):  global doc, extractor, totalLines, totalResItemCnt, totalXmlFileCnt  global totalErrorCnt, errorFileList  global xmlRoot  for i in os.listdir(path):    if i[-3:] == 'xml':      totalXmlFileCnt += 1      try:        #先把xml的encoding由gb2312轉(zhuǎn)換為utf-8        replaceXmlEncoding(path + '//' + i)        #再提取xml文檔中需要的信息        info = extractor(path + '//' + i)        #在上述兩行代碼沒有出現(xiàn)異常的基礎(chǔ)上再創(chuàng)建節(jié)點        #print(info)        #print(type(i))        xmlNode = doc.createElement("XmlFile")        xmlRoot.appendChild(xmlNode)        xmlName = doc.createElement("Filename")        xmlName.setAttribute('Value', i)        #xmlName.appendChild(doc.createTextNode(i))        xmlNode.appendChild(xmlName)        filePath = doc.createElement("Filepath")        filePath.setAttribute('Value', path[34:])        #filePath.appendChild(doc.createTextNode(path[1:]))        xmlNode.appendChild(filePath)        titleNode = doc.createElement("Title")        titleNode.setAttribute('Value', str(info['Title']))        #titleNode.appendChild(doc.createTextNode(str(info['Title'])))        xmlNode.appendChild(titleNode)        chsNode = doc.createElement("ChineseTip")        chsNode.setAttribute('Value', str(info['ChineseTip']))        #chsNode.appendChild(doc.createTextNode(str(info['Chinese'])))        xmlNode.appendChild(chsNode)        resItemNode = doc.createElement("ResItemCount")        resItemNode.setAttribute('Value', str(info['ResItemCount']))        #resItemNode.appendChild(doc.createTextNode(str(info['ResItemCount'])))        xmlNode.appendChild(resItemNode)        lineNode = doc.createElement("LineCount")        lineNode.setAttribute('Value', str(info['Line']))        #lineNode.appendChild(doc.createTextNode(str(info['Line'])))        xmlNode.appendChild(lineNode)        descNode = doc.createElement("Description")        descNode.setAttribute('Value', '')        #descNode.appendChild(doc.createTextNode(''))        xmlNode.appendChild(descNode)      except Exception as errorDetail:        totalErrorCnt += 1        errorFileList.append(path + '//' + i)        print(path + '//' + i, errorDetail)    if os.path.isdir(path + '//' + i):      myWalkDir(level+1, path + '//' + i)if __name__ == "__main__":  path = os.getcwd() + '//themes'  myWalkDir(0, path)  print(totalXmlFileCnt, totalErrorCnt)  #print(doc.toprettyxml(indent = "  "))  resultXml = open("./xmlResourceList.xml", "w")  resultXml.write(doc.toprettyxml(indent = "  "))  resultXml.close()            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 会宁县| 安远县| 商丘市| 广汉市| 浪卡子县| 桃园市| 平利县| 融水| 丹棱县| 延庆县| 萝北县| 临汾市| 宜阳县| 郑州市| 泰顺县| 锡林郭勒盟| 石家庄市| 吴旗县| 河西区| 萍乡市| 永川市| 繁峙县| 措美县| 香港| 宜阳县| 三门峡市| 基隆市| 正蓝旗| 高尔夫| 晋江市| 连城县| 长阳| 博乐市| 三穗县| 祁阳县| 吐鲁番市| 莱阳市| 奉节县| 叙永县| 福清市| 蛟河市|