python获取天气数据_python 获取天气信息,并绘制曲线

#-*- 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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值