如何通过xmlements的属性限制循环?

2024-05-13 19:06:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我觉得我被卡住了,我真的很感激各种形式的帮助和指导。在

我从年份号(诺维根天气预报)。它包含几个元素,其中包含一天中不同时间的天气预报。它每天有3个报告,但我只想用其中一个,我想打印出未来7天的天气。到目前为止,我已经打印出了一整天的天气,或者只有一天。然而,我还没想好如何从错误的时间段中“挑出”那些。在

这是我最近的一次尝试,只得到三份报告中的一份。每一份报告都有三个元素,它们的独特之处在于它们的属性。我将在代码下面显示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”的元素中获取元素“temperature”,得到period=“2”:

^{pr2}$

你们可以得到和我第一次展示的一样的元素。下载链接:http://www.yr.no/stad/Sverige/Stockholm/Stockholm/varsel.xml


Tags: 代码tree元素链接报告counterxmltemp
2条回答

你应该首先迭代“时间”元素,根据你的需要过滤它们。之后,您可以迭代“temperature”子元素。像这样:

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的筛选:

^{pr2}$

现在有python-yr模块可用 而且很容易使用。它从年份号在

看看这个: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))

相关问题 更多 >