【问题标题】:python parse xml蟒蛇解析xml
【发布时间】:2012-10-23 14:16:43
【问题描述】:

我有一个可以解析温度、露点、高度计等的基本脚本。但是,如何解析像天空条件这样的条件字符串?我想解析数据并打印:例如“天空条件:2000 英尺 AGL 时很少”。

import xml.etree.ElementTree as ET
from urllib import urlopen

link = urlopen('http://weather.aero/dataserver_current/httpparam?dataSource=metars&       requestType=retrieve&format=xml&stationString=KSFO&hoursBeforeNow=1')

tree = ET.parse(link)
root = tree.getroot()

data = root.findall('data/METAR')
for metar in data:
    print metar.find('temp_c').text

【问题讨论】:

  • 您可能应该包含一个说明性的 XML 示例。

标签: python xml parsing xml-parsing elementtree


【解决方案1】:

您正在检索的页面具有如下结构:

<METAR>
  <!-- snip -->
  <sky_condition sky_cover="FEW" cloud_base_ft_agl="2000"/>
  <sky_condition sky_cover="BKN" cloud_base_ft_agl="18000"/>
</METAR>

所以您要问的是如何提取 XML 属性。 The xml.etree.ElementTree docs 声明这些存储在一个名为 attrib 的字典中。所以你的代码看起来像这样:

data = root.findall('data/METAR')
for sky in data.findall('sky_condition'):
    print "Sky Condition: {0} at {1} ft AGL".format(
        sky.attrib['sky_cover'],
        sky.attrib['cloud_base_ft_agl']
      )

【讨论】:

  • 啊,打败我了 :) 如果你想进一步减少行数,你可以试试print 'Sky Condition: {sky_cover} at cloud_base_ft_agl}'.format(**sky.attrib),但你的更适合“显式优于隐式”模型。
  • @RocketDonkey 感觉应该有办法做到这一点。我只是忘记了“取消映射”运算符(**)。 +1
  • 哈,我认为你的版本在解释方面做得更好,所以 +1 回 atcha :)
猜你喜欢
  • 2020-06-05
  • 1970-01-01
  • 1970-01-01
  • 2010-10-27
  • 2010-10-21
  • 2016-05-28
  • 2014-08-01
  • 2021-06-28
  • 1970-01-01
相关资源
最近更新 更多