gpt4 book ai didi

python - 将 Excel xml 读取到字典

转载 作者:太空宇宙 更新时间:2023-11-03 19:25:42 24 4
gpt4 key购买 nike

我想将简单的 Excel xml 文件读取到字典中。我尝试使用 xlrd 7.1 但它返回格式错误。现在我尝试使用 xml.etree.ElementTree ,但也没有成功。我无法更改 .xml 文件的结构。这是我的代码:

<?xml version="1.0" encoding="UTF-8"?>
-<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:html="http://www.w3.org/TR/REC-html40">
-<Styles>
-<Style ss:Name="Normal" ss:ID="Default">
<Alignment ss:Vertical="Bottom"/>
<Borders/>
<Font ss:FontName="Verdana"/>
<Interior/>
<NumberFormat/>
<Protection/>
</Style> -<Style ss:ID="s22">
<NumberFormat ss:Format="General Date"/>
</Style>
</Styles> -<Worksheet ss:Name="Linkfeed">
-<Table>
-<Row>
-<Cell>
<Data ss:Type="String">ID</Data>
</Cell> -<Cell>
<Data ss:Type="String">URL</Data>
</Cell>
</Row> -<Row>
-<Cell>
<Data ss:Type="String">22222</Data>
</Cell> -<Cell>
<Data ss:Type="String">Hello there</Data>
</Cell>
</Row>
</Table>
</Worksheet>
</Workbook>

阅读:

import xml.etree.cElementTree as etree

def xml_to_list(fname):
with open(fname) as xml_file:
tree = etree.parse(xml_file)

for items in tree.getiterator(tag="Table"):
for item in items: # Items is None!
print item.text

更新,现在可以了,但是如何排除垃圾?

def xml_to_list(fname):
with open(fname) as xml_file:
tree = etree.iterparse(xml_file)
for item in tree:
print item[1].text

最佳答案

使用 if 语句排除“垃圾”:

def xml_to_list(fname):
with open(fname) as xml_file:
tree = etree.iterparse(xml_file)
for item in tree:
if item[1].text.strip() != '-':
print item[1].text

关于python - 将 Excel xml 读取到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8214511/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com