xml和pandas結合處理的一個小例子-待完善


#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import pandas
import json
import xml.etree.ElementTree as ET

# 讀取csv對象為pandas
loc_info = pandas.read_csv('湖南花瑤花化妝品有限公司(51616興業銀行)2014.csv')
# 列值運算
loc_info["size_1"] = loc_info["right"] - loc_info["left"]
loc_info["size_2"] = loc_info["bottom"] - loc_info["top"]
# 刪除列
loc_info = loc_info.drop("right",1)
loc_info = loc_info.drop("bottom",1)
loc_json = loc_info.to_json(orient='index')

# 組裝xml需要的屬性鍵值對
loc_list = []
loc_dict = json.loads(loc_json)
for loc in loc_dict.values():
    position = str(loc['left']) + ',' + str(loc['top'])
    size = str(loc['size_1']) + ',' + str(loc['size_2'])
    loc_value = {
                "Position": position,
                "Size": size,
                "StrokeThickness": "1",
                "Shape": "BasicShapes.Rectangle",
                "Content": loc['value'],
                "ItemKind": "DiagramShape"
            }
    loc_list.append(loc_value)

# 獲取xml根節點
tree = ET.parse("origin.xml")
root = tree.getroot()
children = root[0][0][0]

# 添加子節點
for i in range(len(loc_list)):
    item_name = "Item"+str(i)
    ET.SubElement(children,item_name,loc_list[i])

ET.dump(children)

# 創建新xml對象
tree.write('test_demo.xml')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM