Discuss / Python / 参考了几个高手的作业, 自己增强了一下, 取值上按日期来保证准确性和可拓展性

参考了几个高手的作业, 自己增强了一下, 取值上按日期来保证准确性和可拓展性

Topic source

一雷叔一

#1 Created at ... [Delete] [Delete and Lock User]

from xml.parsers.expat import ParserCreate from datetime import datetime, timedelta

class WeatherSaxHandler(object):

def __init__(self):
    self._weather = {}

def start_element(self, name, attrs):

    if name == 'yweather:location':
        self._weather['city'] = attrs['city']
        self._weather['country'] = attrs['country']
    elif name == 'yweather:condition':
        self._weather['condition'] = attrs
    elif name == 'yweather:forecast':
        self._weather[attrs['date']] = attrs

def end_element(self, name):
    pass

def char_data(self, text):
    pass

def parse_weather(data):

handler = WeatherSaxHandler()
parser = ParserCreate()
parser.StartElementHandler = handler.start_element
parser.EndElementHandler = handler.end_element
parser.CharacterDataHandler = handler.char_data
parser.Parse(data)

Dweather = {}
Dweather['today'] = {}
Dweather['tomorrow'] = {}

condition = handler._weather['condition']['date'].split(',')[1].strip().split(' ')
today = condition[0] + ' ' + condition[1] + ' ' + condition[2]
tomorrow = datetime.strptime(today,'%d %b %Y') + timedelta(days=1)

Dweather['city'] = handler._weather['city']
Dweather['country'] = handler._weather['country']
Dweather['today']['text'] = handler._weather[today]['text']
Dweather['today']['low'] = handler._weather[today]['low']
Dweather['today']['high'] = handler._weather[today]['high']

Dweather['tomorrow']['text'] = handler._weather[tomorrow.strftime('%d %b %Y')]['text']
Dweather['tomorrow']['low'] = handler._weather[tomorrow.strftime('%d %b %Y')]['low']
Dweather['tomorrow']['high'] = handler._weather[tomorrow.strftime('%d %b %Y')]['high']

return Dweather

if name == 'main': print(parse_weather(data))


  • 1

Reply