LXML,如何将多个属性集转换为列表
我遇到了一个类似的问题:
我的XML数据看起来是这样的:
<?xml version="1.0" encoding="utf-8"?>
<Basic>
<Segment>
<Sample value="12" data2="25" data3="23"/>
<Sample value="13" data2="0" data3="323"/>
<Sample value="14" data2="2" data3="3"/>
</Segment>
</Basic>
用Python最简单的方法是什么,能把这些 datax
的值提取到列表里。
比如说: data2 = ['25','0','2']
3 个回答
0
这里讲的是如何使用标准库中的 cElementTree
。
import sys
from collections import defaultdict
from xml.etree import cElementTree as etree
d = defaultdict(list)
for ev, el in etree.iterparse(sys.stdin):
if el.tag == 'Sample':
for name in "value data2 data3".split():
d[name].append(el.get(name))
print(d)
输出结果
{'data2': ['25', '0', '2'],
'data3': ['23', '323', '3'],
'value': ['12', '13', '14']}
如果你使用的是 lxml.etree
,那么你可以这样做:etree.iterparse(file, tag='Sample')
,这样就能直接选择 Sample
这个元素了。也就是说,你可以省去 if el.tag == 'Sample'
这个判断条件。
1
获取属性值最简单的方法是使用 etree.Element.get('属性名'):
from lxml import etree
s = '''<?xml version="1.0" encoding="utf-8"?>
<Basic>
<Segment>
<Sample value="12" data2="25" data3="23"/>
<Sample value="13" data2="0" data3="323"/>
<Sample value="14" data2="2" data3="3"/>
</Segment>
</Basic>'''
# ❗️for python2
# tree = etree.fromstring(s)
# ❗️for python3
tree = etree.fromstring(s.encode("utf-8"))
samples = tree.xpath('//Sample')
print([sample.get('data2') for sample in samples])
>>> ['25', '0', '2']
5
使用xpath:
from lxml import etree
from collections import defaultdict
from pprint import pprint
doc="""<?xml version="1.0" encoding="utf-8"?>
<Basic>
<Segment>
<Sample value="12" data2="25" data3="23"/>
<Sample value="13" data2="0" data3="323"/>
<Sample value="14" data2="2" data3="3"/>
</Segment>
</Basic>
"""
el = etree.fromstring(doc)
data2 = el.xpath('//@data2')
dataX = el.xpath('//@*[starts-with(name(), "data")]')
print data2
print dataX
# With iteration over Sample elements, like in J.F. Sebastian answer, but with XPath
d = defaultdict(list)
for sample in el.xpath('//Sample'):
for attr_name, attr_value in sample.items():
d[attr_name].append(attr_value)
pprint(dict(d))
输出结果:
['25', '0', '2']
['25', '23', '0', '323', '2', '3']
{'data2': ['25', '0', '2'],
'data3': ['23', '323', '3'],
'value': ['12', '13', '14']}