python-3.x - xml到多个熊猫数据框
问题描述
我想从 XML 中提取数据并将其转换为 Multiple Pandas DataFrame,我尝试使用 Element Tree xml 导入并打印出标签和文本(仅限 2 列)我无法弄清楚如何将其拆分为多个数据框,
<?xml version="1.0" encoding="ISO-8859-1"?>
<spec:zzz>
<xxx>
<class>
<table_name>
<attributes>
<aaa>0</aaa>
<bbb>1</bbb>
<ccc>
<element>
<ccc1>0</ccc1>
<ccc2>0</ccc2>
<ccc3>3</ccc3>
</element>
</ccc>
</attributes>
</table_name>
<table_name>
<attributes>
<aaa>0</aaa>
<bbb>0</bbb>
<ccc>
<element>
<ccc1>0</ccc1>
<ccc2>0</ccc2>
<ccc3>3</ccc3>
</element>
</ccc>
<ddd>4</ddd>
</attributes>
</table_name>
</class>
<class>
<table_name1>
<attributes>
</attributes>
</table_name1>
</class>
<class>
<table_name2>
<attributes>
<eee>0</eee>
<fff></fff>
<ggg></ggg>
</attributes>
</table_name2>
</class>
</xxx>
</spec:zzz>
表格样本:
table_name table_name1 table_name2
|aaa| bbb | ccc | ddd| |eee |fff | ggg |
|0 |1 |(0,0,3)| | |0 | | |
|0 |0 |(0,0,3)|4 |
解决方案
尝试这个。
from simplified_scrapy import utils, SimplifiedDoc
xml = '''
your xml
'''
doc = SimplifiedDoc(xml)
tablenames = doc.selects('class').children
for tablename in tablenames:
table = tablename.child.children
rows = []
for attributes in table:
# rows.append([attr.text for attr in attributes])
row = []
for attr in attributes:
if attr.child:
row.append(','.join(attr.child.children.text))
else:
row.append(attr.text)
rows.append(row)
print (tablename[0].tag, rows)
结果:
table_name [['0', '1', '0,0,3'], ['0', '0', '0,0,3', '4']]
table_name1 [[]]
table_name2 [['0', '', '']]
处理多个文件
from simplified_scrapy import utils, SimplifiedDoc
xmlDir = 'test/'
xmls = utils.getSubFile(xmlDir)
for x in xmls:
xml = utils.getFileContent(x)
# xml = '''your xml'''
doc = SimplifiedDoc(xml)
tablenames = doc.selects('class').children
for tablename in tablenames:
table = tablename.child.children
rows = []
for attributes in table:
# rows.append([attr.text for attr in attributes])
row = []
for attr in attributes:
if attr.child:
row.append(','.join(attr.child.children.text))
else:
row.append(attr.text)
rows.append(row)
print (tablename[0].tag, rows)
推荐阅读
- javascript - 如何在 JavaScript 中将数组 (arr1) 的值推送到新的空数组 (arr2) 中?
- dart - 如何重置 ScanStreamTransformer 累加器?
- c - 为 32 位类型设置到给定位置的计数位
- wolfram-mathematica - Raspberry Pi 上的 Mathematica 无法读取简单的文本文件
- bash - awk 或类似命令,用于获取最后一列并在 Bash 中对其执行一些操作
- c++ - 修改上一行 c++
- r - 可以在 R 中使用 gganimate 对多边形填充进行动画处理吗?
- android - 使用 Moshi 的 Kotlin 代码生成的困难
- apollo - 在另一个查询中重用从一个查询缓存的数据
- arrays - Powershell:类似运算符的神秘行为