Discuss / Python / 交作业

交作业

Topic source
# -*-coding: gbk
from xml.parsers.expat import ParserCreate
class WeatherSaxHandler(object):
    def __init__(self):
        self.weather_info = {}
        self.curdate = 0

    def start_element(self,name,attrs):
        if name == 'yweather:location':
            self.weather_info['city'] = attrs['city']
            self.weather_info['country'] = attrs['country']
        elif name == 'yweather:forecast':
            if self.curdate == 0:
                self.weather_info['today'] = self.setup_weather(attrs)
            elif self.curdate == 1:
                self.weather_info['tomorrow'] = self.setup_weather(attrs)
            self.curdate+= 1

    def setup_weather(self,weather_info_from_media):
        cur_weather = {}
        cur_weather['text'] = weather_info_from_media['text']
        cur_weather['low'] = float(weather_info_from_media['low'])
        cur_weather['high'] =float(weather_info_from_media['high'])
        return cur_weather


def parse_weather(xml):
    handler = WeatherSaxHandler()
    parser  = ParserCreate()
    parser.StartElementHandler = handler.start_element
    parser.Parse(xml)
    return handler.weather_info

  • 1

Reply