Python 将XML文件转换为CSV
我正在与下面的案例作斗争。我有一个以下格式的XML文件:Python 将XML文件转换为CSV,python,xml,csv,data-conversion,format-conversion,Python,Xml,Csv,Data Conversion,Format Conversion,我正在与下面的案例作斗争。我有一个以下格式的XML文件: <event> <attribute type="NAME">John</attribute> <attribute type="TASK">Buy</attribute> <attribute type="DATE">12052017</attribute> </event> <event> <attribu
<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>
我正在使用我为Notepad++编写的一个小Python脚本,它搜索并删除字符串中不应该出现的所有内容。例如:
editor.rereplace('\r\n <attribute type="NAME">', '');
不区分属性任务和资源
我检查了不同的主题,但没有一个真正涵盖了我的问题。有人能帮我一个便宜的把戏吗,或者给我指一个工具。数据必须是有效的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>
'''
结果将是:
[{'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)
数据必须是有效的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>
'''
结果将是:
[{'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)
对于我的项目,我使用以下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()
对于我的项目,我使用以下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()
CSV在哪里?CSV在哪里?如果有嵌套节点怎么办?如果有嵌套节点怎么办?