题目
将 第 0016 题中的 numbers.xls 文件中的内容写到 numbers.xml 文件中,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<numbers>
<!--
数字信息
-->
[
[1, 82, 65535],
[20, 90, 13],
[26, 809, 1024]
]
</numbers>
</root>
分析
和0017题,0018题,都是一样的,这次用pandas封装好的read_excel
去读取表格内容,建立xml依旧用lxml。
pip install pandas xlrd lxml
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| import pandas as pd from lxml import etree
def read_xls(xlsname): df = pd.read_excel(xlsname, header=None) d = df.to_dict(orient='split')['data'] return "\n\t[\n\t\t{},\n\t\t{},\n\t\t{}\n\t]\n".format(d[0], d[1], d[2])
def write_xml(xmlname, data, comment): root = etree.Element('root')
comm = etree.Comment(comment) root.append(comm)
child = etree.SubElement(root, xmlname) child.text = data
tree = etree.ElementTree(root)
tree.write( xmlname + '.xml', pretty_print=True, xml_declaration=True, encoding='utf-8')
if __name__ == "__main__": comment = '数字信息' data = read_xls('numbers.xls') write_xml('numbers', data, comment)
|
参考