【发布时间】:2016-09-07 18:55:37
【问题描述】:
我是 python 新手。实际上我能够解析一个 xml,但不知道如何将它写入 excel。
示例 xml:
<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>Light Belgian waffles covered with strawberries and whipped cream</description>
<calories>900</calories>
</food>
我的代码:
import xml.etree.ElementTree as etree
xmld = etree.parse('simple.xml')
root = xmld.getroot()
for child in root:
for children in child:
print children.tag," : % s" %children.text
输出:
name : Belgian Waffles
price : $5.95
description : Two of our famous Belgian Waffles with plenty of real maple syrup
calories : 650
name : Strawberry Belgian Waffles
price : $7.95
description : Light Belgian waffles covered with strawberries and whipped cream
calories : 900
需要像这样写进excel里
'tags' 进入 A 列,'values' 进入 B 列 enter image description here
尝试使用 xlwt 或 openpyxl 或 pandas..但没有运气...请帮助..
【问题讨论】:
-
尝试从您的输出中创建一个字典,然后从中创建一个数据框并将其写入一个 excel 文件。
-
这个问题是真实的还是你得到了答案?
-
嗨,弗拉德...是的,尝试使用 openpyxl,例如:" for row in zip({children.tag},{children.text}): ws.append(row) wb.save("simple .xls") " 现在我可以得到预期的输出了。非常感谢!!!!
标签: python-3.x pandas openpyxl xlwt