我一直致力于将XML解析为dict列表,并将其转换为类似熊猫的数据帧。你知道吗
# -*- coding: utf-8 -*-
import pandas as pd
"""
It's very important for parsing!
"""
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import xml.etree.cElementTree as ET
from table import Table
def xml_to_pd(xml):
tree = ET.fromstring(xml)
xmltag = tree.tag
doc_dict = {}
res = []
for doc in tree.iter():
if doc.attrib:
if doc_dict not in res and len(doc_dict)>0:
res.append(doc_dict)
doc_dict = {}
doc_dict = (doc.attrib)
if doc.text:
key = doc.tag
value = doc.text
doc_dict[key] = (value)
else:
if doc.text:
key = doc.tag
value = doc.text
doc_dict[key] = (value)
else:
if doc_dict != {}:
if doc_dict not in res:
res.append(doc_dict)
doc_dict = {}
if doc_dict != {}:
if doc_dict not in res:
res.append(doc_dict)
doc_dict = {}
df = pd.DataFrame(res)
return df
table = pd.DataFrame()
allxml = ['<markets><market id="1">MMVB</market><market id="4">FORTS</market><market id="15">ETS</market></markets>',
'<sec_info_upd><secid>1538</secid><seccode>SV16BL5</seccode><market>4</market><bgo_c>11908.97</bgo_c><bgo_nc>10307.27</bgo_nc><bgo_buy>4789.49</bgo_buy></sec_info_upd>',
'<quotes><quote secid="3630"><board>FUT</board><seccode>SiZ5</seccode><price>68079</price><buy>-1</buy></quote><quote secid="3630"><board>FUT</board><seccode>SiZ5</seccode><price>68132</price><buy>2</buy></quote></quotes>']
for xml in allxml:
res = xml_to_pd(xml)
for r in res:
table = pd.concat([table, res])
print '\n\r'
print table
我们的想法是从每个XML表达式构建一个表,但结果中出现了奇怪的混合,而且不太确定是否正确。你知道吗
请不要关心Pandas,实际上我将使用另一个轻量级的存储表对象来接受dict列表,就像Pandas DataFrame一样。你知道吗
另外,它对时间也非常关键,因为xml提要每10毫秒从股市提供一次。所以,问题是:我应该如何正确快速地完成这个任务?你知道吗
我真的需要你的帮助,因为我完全陷入了xml的地狱。 提前谢谢。你知道吗
以下是我的(丑陋的)解决方案:
一年后更新。
相关问题 更多 >
编程相关推荐