python - 如何在 python 3.5 上使用 ElementTree 将 csv 转换为 xml 文件
问题描述
我是 Python 新手,对这门语言没有太多经验。我有一个 CSV 文件,我必须从其中将数据转换为 XML 结构。我想用 Pandas 和ElementTree
.
我阅读了一个教程,但我无法理解代码的结构。
CSV 文件看起来像这样
test_name,health_feat,result
test_1,20,1
test_2,23,1
test_3,24,0
test_4,12,1
test_5,45,0
test_6,34,1
test_7,78,1
test_8,23,1
test_9,12,1
test_10,12,1
最终的 XML 文件应如下所示,但我不确定应用时如何处理属性ElementTree
:
<xml version = '1.0' encoding = 'UTF-8'>
<Test Testname = 'test_1' >
<Health_Feat>20</health_feat>
<Result>1</Result>
</Test>
<Test Testname = 'test_2'>
<Health_Feat>23</Healt_Feat>
<Result>1</Result>
</Test>
<Test Testname = 'test_3'>
<Health_Feat>24</Healt_Feat>
<Result>0</Result>
</Test>
<Test Testname = 'test_4'>
<Health_Feat>30</Healt_Feat>
<Result>1</Result>
</Test>
<Test Testname = 'test_5'>
<Health_Feat>12</Healt_Feat>
<Result>1</Result>
</Test>
<Test Testname = 'test_6'>
<Health_Feat>45</Healt_Feat>
<Result>1</Result>
</Test>
<Test Testname = 'test_7'>
<Health_Feat>34</Healt_Feat>
<Result>0</Result>
</Test>
<Test Testname = 'test_8'>
<Health_Feat>78</Healt_Feat>
<Result>1</Result>
</Test>
<Test Testname = 'test_9'>
<Health_Feat>23</Healt_Feat>
<Result>1</Result>
</Test>
<Test Testname = 'test_10'>
<Health_Feat>12</Healt_Feat>
<Result>1</Result>
</Test>
</Tests>
目前我尝试过这样的事情,但我不知道如何告诉程序从 csv 中获取哪一行。
from lxml import etree as et
import uuid
df = pd.read_csv('mytests.csv', sep = ',')
root = et.Element(Tests)
for index, row in df.iterrows():
if row['test_name'] == 'test_1':
Test = et.SubElement(root, 'Test')
Test.attrib['fileUID']
health_feat = et.subElement('health_feat')
Result = et.subElement('Result')
else:
Tests = et.subElement(root, 'Tests')
et.ElementTree(root).write('mytests.xml', pretty_print = True, xml_declaration = True, encoding = 'UTF-8', standalone = None)
解决方案
像这样的东西:
import pandas as pd
df = pd.read_csv('your_csv.csv', sep=',')
def csv_to_xml(row):
return """<Test Testname="%s">
<Health_Feat>%s</Health_Feat>
<Result>%s</Result>
</Test>""" % (row.test_name, row.health_Feat, row.Result)
并在 for 循环中为 csv 的每一行调用该函数
推荐阅读
- session - 如何验证 ColdFusion .cfc 页面中的有效会话和会话数据?
- c++ - 在 c++17 中过滤类型的元组
- javascript - 获取图像尺寸并将它们应用于另一个图像
- mysql - 存储过程无法按我的意愿工作
- node.js - 将 PDF 上传到 Amazon S3 并在浏览器中显示
- html - 使用高级逻辑查询 Html 层次结构
- python - pandas - 通过重复值连接列
- kubernetes - 状态集的就绪探测,而不是单个 pod/容器
- php - 在 Laravel 微服务中解码 JWT 并创建经过身份验证的用户,并与本地用户数据合并
- c# - 从列表框中选择对象并在另一个列表框中显示相应的对象