#-*- coding: utf-8 -*-
#功能:查询城市天气
importrequests, json, refrom matplotlib importpyplot as plt#获取城市代码
defgetCityCode(city):
url= 'http://toy1.weather.com.cn/search?cityname=' +city
r=requests.get(url)if len(r.text) > 4:
json_arr= json.loads(r.text[1:len(r.text) - 1])
code= json_arr[0]['ref'][0:9]returncodeelse:return "000000000"
#获取城市天气信息
defgetWeatherInfo(city):
code=getCityCode(city)
url= 'http://t.weather.sojson.com/api/weather/city/' +code
r=requests.get(url)
info=r.json()
weather={}if info['status'] == 200:
weather['城市:'] = info['cityInfo']['parent'] + info['cityInfo']['city']
weather['时间:'] = info['time'] + ' ' + info['data']['forecast'][0]['week']
weather['温度:'] = info['data']['forecast'][0]['high'] + ' ' + info['data']['forecast'][0]['low']
weather['天气:'] = info['data']['forecast'][0]['type']else:
weather['错误:'] = '[' + city + ']不存在!'
returnweather#打印天气信息
defprintWeatherInfo(weather):for key inweather:print(key +weather[key])#获取未来气温
defgetTemperatures(city):
code=getCityCode(city)
url= 'http://t.weather.sojson.com/api/weather/city/' +code
r=requests.get(url)
info=r.json()
temperatures={}if info['status'] == 200:
forecast= info['data']['forecast']for i inrange(len(forecast)):
dayinfo=forecast[i]
high= int(re.findall(r'\d+', dayinfo['high'])[0])
low= int(re.findall(r'\d+', dayinfo['low'])[0])
temperatures[dayinfo['ymd']] =[high, low]else:
temperatures['错误:'] = '[' + city + ']不存在!'
returntemperatures#打印未来气温
defprintTemperatures(temperatures):if '错误:' not intemperatures.keys():for key intemperatures:print(key + '高温:' + str(temperatures[key][0]) + '低温:' + str(temperatures[key][1]))#绘制未来气温折线图
defdrawTemperatureLineChart():
temperatures=getTemperatures(city)if '错误:' not intemperatures.keys():
dates=[]
highs=[]
lows=[]for key intemperatures:
dates.append(key)
highs.append(temperatures[key][0])
lows.append(temperatures[key][1])
fig= plt.figure(dpi=81, figsize=(5, 4))
plt.xlabel('Date (YYYY-MM-DD)', fontsize=10)
plt.ylabel("Temperature (℃)", fontsize=10)
fig.autofmt_xdate()
plt.plot(dates, highs, c='red', alpha=0.5)
plt.plot(dates, lows, c='blue', alpha=0.5)
plt.show()
city= input('输入城市名:')
printWeatherInfo(getWeatherInfo(city))
printTemperatures(getTemperatures(city))
drawTemperatureLineChart()