簡體   English   中英

將XML文件轉換為CSV

[英]Convert XML-file to CSV

我在處理以下情況。 我有以下格式的XML文件:

<event>
  <attribute type="NAME">John</attribute>
  <attribute type="TASK">Buy</attribute>
  <attribute type="DATE">12052017</attribute>
</event>
<event>
  <attribute type="NAME">John</attribute>
  <attribute type="RESOURCE">Dollar</attribute>
  <attribute type="DATE">13052017</attribute>
</event>

我需要將其轉換為CSV文件。 結果應該是:

John,Buy,,12052017
John,,Dollar,13052017

我正在使用為Notepad ++編寫的Python小腳本,該腳本搜索並刪除字符串中不應該包含的所有內容。 例如:

editor.rereplace('\r\n  <attribute type="NAME">', '');

這可以正常工作,但是會弄亂屬性的順序(因為如果找不到<attribute type="TASK">它不會放置多余的,那么結果是:

John,Buy,12052017
John,Dollar,13052017

屬性TASK和RESOURCE之間沒有區別。

我檢查了不同的主題,但沒有一個問題能真正解決我的問題。 可以幫我一個便宜的把戲或為我指出一個工具。

對於我的項目,我正在使用以下python腳本:

import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET


def xml_to_csv(path):
    xml_list = []
    for xml_file in glob.glob(path + '/*.xml'):
        tree = ET.parse(xml_file)
        root = tree.getroot()
        for member in root.findall('object'):
            value = (root.find('filename').text,
                     int(root.find('size')[0].text),
                     int(root.find('size')[1].text),
                     member[0].text,
                     int(member[4][0].text),
                     int(member[4][1].text),
                     int(member[4][2].text),
                     int(member[4][3].text)
                     )
            xml_list.append(value)
    column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']
    xml_df = pd.DataFrame(xml_list, columns=column_name)
    return xml_df


def main():
    for directory in ['train','test']:
        image_path = os.path.join(os.getcwd(), 'images/{}'.format(directory))
        xml_df = xml_to_csv(image_path)
        xml_df.to_csv('data/{}_labels.csv'.format(directory), index=None)
        print('Successfully converted xml to csv.')


main()

數據必須是有效的xml文檔

data = '''<?xml version="1.0"?>
<data>
<event>
  <attribute type="NAME">John</attribute>
  <attribute type="TASK">Buy</attribute>
  <attribute type="DATE">12052017</attribute>
</event>
<event>
  <attribute type="NAME">John</attribute>
  <attribute type="RESOURCE">Dollar</attribute>
  <attribute type="DATE">13052017</attribute>
</event>
</data>
'''

你可以做這樣的事情來提取你需要的東西

import xml.etree.ElementTree as ET

doc = ET.fromstring(data)

mycsv = []


for event in doc:
    row = {}
    for attr in event:
        if attr.tag == 'attribute':
            print attr.tag, attr.attrib, attr.text
            row[attr.attrib['type']] = attr.text
    mycsv.append(row)

結果將是:

[{'DATE': '12052017', 'TASK': 'Buy', 'NAME': 'John'}, {'DATE': '13052017', 'RESOURCE': 'Dollar', 'NAME': 'John'}]

並寫入csv文件

import csv

keys = ['NAME', 'TASK', 'RESOURCE', 'DATE']
with open('result.csv', 'wb') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(mycsv)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM