0

我正在为以下情况而苦苦挣扎。我有一个以下格式的 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 之间没有区别。

我检查了不同的主题,但没有一个真正涵盖我的问题。可以帮我一个便宜的把戏或给我一个工具。

4

2 回答 2

2

对于我的项目,我正在使用这个 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()
于 2017-09-01T09:37:37.003 回答
1

数据必须是有效的 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)
于 2017-05-12T12:29:31.590 回答