首页 文章

如何通过其属性限制xml元素的循环?

提问于
浏览
0

我觉得自己被困住了,非常感谢所有形式的帮助和指导 .

我从yr.no下载了一个XML(norweigan天气预报) . 它包含几个元素,包含一天中不同时间的天气报告 . 它每天有3个报告,但我只想使用其中一个,我想打印出未来7天的天气 . 到目前为止,我已经设法打印出所有日子的天气,或者只有一个 . 然而,我没有想过如何从错误的时间段“理清”那些 .

这是我最近尝试获得3个报告中的1个 . 每个报告都有三个要素,它们的独特之处在于它们的属性 . 我将在我的代码下面显示xml中的几行 . 如果你想下载整个xml来查看结构,我会在底部放一个链接 .

我的最新尝试:

with open('Stockholm.xml', 'rt') as wreport:
    tree = ET.parse(wreport)

for temp in tree.getiterator("temperature"):
    counter = 2
    if counter == 0 or counter == 1:
        counter += 1
    elif counter == 2:
        counter -= 2
        print "In Stockholm it will today be %s celcius" % (temp.get("value"))

XML,我希望从名为“time”的前7个元素中得到元素“temperature”,得到句点=“2”:

<forecast>
 <tabular>
   <time from="2014-01-03T12:00:00" to="2014-01-03T18:00:00" period="2">
    <!--
    Valid from 2014-01-03T12:00:00 to 2014-01-03T18:00:00 
    -->
    <symbol number="4" name="Skya" var="04"/>
    <precipitation value="0.1" minvalue="0.1" maxvalue="0.2"/>
    <!--  Valid at 2014-01-03T12:00:00  -->
    <windDirection deg="163.3" code="SSE" name="Sør-søraust"/>
    <windSpeed mps="4.6" name="Lett bris"/>
    <temperature unit="celsius" value="4"/>
    <pressure unit="hPa" value="1007.0"/>
   </time>
<time from="2014-01-03T18:00:00" to="2014-01-04T00:00:00" period="3">...</time>
<time from="2014-01-04T00:00:00" to="2014-01-04T06:00:00" period="0">...</time>
<time from="2014-01-04T06:00:00" to="2014-01-04T12:00:00" period="1">...</time>

在所有这些中你可以获得我第一次展示的相同元素 . 点击此处下载链接:http://www.yr.no/stad/Sverige/Stockholm/Stockholm/varsel.xml

2 回答

  • 0

    这些天有模块 python-yr ,它非常容易使用 . 它从yr.no提供JSON数据

    看看这个:https://github.com/wckd/python-yr

    例:

    #!/usr/bin/env python3
    
    from yr.libyr import Yr
    import dateutil.parser
    
    
    weather = Yr( location_name='Czech_Republic/Central_Bohemia/Kralupy_nad_Vltavou', forecast_link='forecast', )
    
    day_before=""  # days separator print line flag
    
    for forecast in weather.forecast():
    
        day = dateutil.parser.parse(forecast['@from']).strftime("%A")
    
        if day_before != day:
            print()
            day_before = day
    
    
        time_from = dateutil.parser.parse(forecast['@from']).strftime("%d.%m.%Y %H:%M")
    
        time_to = dateutil.parser.parse(forecast['@to']).strftime("%H:%M%p")
        sky = forecast['symbol']['@name']
        wind = forecast['windSpeed']['@name']
        wind_speed = forecast['windSpeed']['@mps']
        precipitation = forecast['precipitation']['@value']
        temperature = forecast['temperature']['@value']
        print("{0:<7} {1}-{2}  {7:>2}°C  {3:<18}, wind {5:<4} m/s, prec.: {6:<3} mm ".format(
                        day,
                        time_from,
                        time_to,
                        sky,
                        wind,
                        wind_speed,
                        precipitation,
                        temperature))
    
  • 1

    您应首先在'time'元素上迭代,以根据您的需要过滤它们 . 之后,您可以迭代'温度'子元素 . 像这样的东西:

    import lxml.etree as etree
    
    with open('Stockholm.xml', 'rt') as wreport:
        xml = etree.parse(wreport)
        for record in xml.iter('time'):
            if record.attrib['period'] == '2':
                for temp in record.iter('temperature'):
                    print 'In Stockholm it will today be %s celcius from %s to %s\n' %
                            (temp.attrib['value'], 
                            record.attrib['from'], 
                            record.attrib['to'])
    

    或者,您可以像过滤一样使用XPath:

    import lxml.etree as etree
    
    with open('Stockholm.xml', 'rt') as wreport:
        xml = etree.parse(wreport)
            for temp in xml.findall('.//time[@period="2"]/temperature'):
                print 'In Stockholm it will today be %s celcius\n' % 
                                temp.attrib['value']
    

相关问题