Discuss / Python / 作业:查询天气

作业:查询天气

Topic source

部分复制自xml篇的作业

# 查询天气
# -*- coding: utf-8 -*-

import urllib.request, urllib.parse
from xml.parsers.expat import ParserCreate

class weatherSaxHandler(object):
    def __init__(self):
        self.location = {}
        self.forcast = []
    def start_element(self, name, attrs):
        if name == 'yweather:location':
            self.location = attrs
            attrs.pop('xmlns:yweather')
        if name == 'yweather:forecast':
            self.forcast.append(attrs)
    def end_element(self, name):
        pass
    def char_data(self,text):
        pass

def parse_weather(xml): # 输入xml字符串,输出天气信息dict
    parser = ParserCreate()
    handler = weatherSaxHandler()
    parser.StartElementHandler = handler.start_element
    parser.EndElementHandler = handler.end_element
    parser.CharacterDataHandler = handler.char_data
    parser.Parse(xml)
    today = {
        'text': handler.forcast[0]['text'],
        'low': int(handler.forcast[0]['low']),
        'high': int(handler.forcast[0]['high'])
    }
    tomorrow = {
        'text': handler.forcast[1]['text'],
        'low': int(handler.forcast[1]['low']),
        'high': int(handler.forcast[1]['high'])
    }
    d = {
        'today': today,
        'tomorrow': tomorrow
    }
    weather = handler.location
    weather.update(d)
    return weather

def get_weather(city): # 输入城市名(拼音)字符串,输出天气dict
    baseurl = "https://query.yahooapis.com/v1/public/yql?"
    yql_query = 'select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="%s")' % city
    yql_url = baseurl + urllib.parse.urlencode({'q':yql_query})
    with urllib.request.urlopen(yql_url) as f:
        city_xml = f.read().decode('utf-8')
    city_weather = parse_weather(city_xml)
    return city_weather

def main():
    city = input('Weather Forecast in City: ')
    print(get_weather(city))

main()

差了一个温度的参数,用来将华氏温度改成摄氏温度

王了妳

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

大神,你怎么知道还要查表写sql


  • 1

Reply