我有一个很长的字符串,其中包含需要分离/提取以进行评估的信息集。
作为一名初级程序员,我知道各种解析操作,如 split() append() remove() 等 - 但我正在努力想出一种将它们组合起来以提取相关数据的逻辑方法......
长字符串...
"<Sets X="s"><B s="1" e="2176" t="-2.0774E4" r="1" /><B s="2177" e="8982" t="-1.8597E4" r="1" /><B s="8983" e="10393" t="-150.22" r="1" /></Sets>"
包含3组需要存储为float值的数据
[Set1] s=1 e=2176 t=-20774 r=1
[Set2] s=2177 e=8982 t=-18597 r=1
[Set3] s=8983 e=10393 t=-150.2 r=1
我希望将每组数据存储为一个列表
Set1 = [1,2176,-20774,1]
Set2 = [2177,8982,-18597,1]
Set3 = [2178,10393,-150.2,1]
注意:组数可能会有所不同
请您参考如下方法:
使用内置 ElementTree从 xml 中提取数据的库:
import xml.etree.ElementTree as ET
data = '<Sets X="s"><B s="1" e="2176" t="-2.0774E4" r="1" /><B s="2177" e="8982" t="-1.8597E4" r="1" /><B s="8983" e="10393" t="-150.22" r="1" /></Sets>'
tree = ET.fromstring(data)
for b in tree.findall('.//B'):
print map(float, itemgetter(*'setr')(b.attrib))
打印:
[1.0, 2176.0, -20774.0, 1.0]
[2177.0, 8982.0, -18597.0, 1.0]
[8983.0, 10393.0, -150.22, 1.0]
