python 获取天气信息,并绘制曲线
import urllib.request import gzip import json print('------天气查询------') def get_weather_data() : city_name = input('请输入要查询的城市名称:') url1 = 'http://wthrcdn.etouch.cn/weather_mini?city='+urllib.parse.quote(city_name) url2 = 'http://wthrcdn.etouch.cn/weather_mini?citykey=101010100' #网址1只需要输入城市名,网址2需要输入城市代码 #print(url1) weather_data = urllib.request.urlopen(url1).read() #读取网页数据 weather_data = gzip.decompress(weather_data).decode('utf-8') #解压网页数据 weather_dict = json.loads(weather_data) #将json数据转换为dict数据 return weather_dict def show_weather(weather_data): weather_dict = weather_data #将json数据转换为dict数据 if weather_dict.get('desc') == 'invilad-citykey': print('你输入的城市名有误,或者天气中心未收录你所在城市') elif weather_dict.get('desc') =='OK': forecast = weather_dict.get('data').get('forecast') print('城市:',weather_dict.get('data').get('city')) print('温度:',weather_dict.get('data').get('wendu')+'℃ ') print('感冒:',weather_dict.get('data').get('ganmao')) print('风向:',forecast[0].get('fengxiang')) print('风级:',forecast[0].get('fengli')) print('高温:',forecast[0].get('high')) print('低温:',forecast[0].get('low')) print('天气:',forecast[0].get('type')) print('日期:',forecast[0].get('date')) print('*******************************') four_day_forecast =input('是否要显示未来四天天气,是/否:') if four_day_forecast == '是' or 'Y' or 'y': for i in range(1,5): print('日期:',forecast[i].get('date')) print('风向:',forecast[i].get('fengxiang')) print('风级:',forecast[i].get('fengli')) print('高温:',forecast[i].get('high')) print('低温:',forecast[i].get('low')) print('天气:',forecast[i].get('type')) print('--------------------------') print('***********************************') show_weather(get_weather_data())
运行
------天气查询------ 请输入要查询的城市名称:北京 城市: 北京 温度: 0℃ 感冒: 昼夜温差较大,较易发生感冒,请适当增减衣服。体质较弱的朋友请注意防护。 风向: 西南风 风级: <![CDATA[<3级]]> 高温: 高温 2℃ 低温: 低温 -6℃ 天气: 多云 日期: 21日星期六 ******************************* 是否要显示未来四天天气,是/否:是 日期: 22日星期天 风向: 无持续风向 风级: <![CDATA[<3级]]> 高温: 高温 5℃ 低温: 低温 -5℃ 天气: 多云 -------------------------- 日期: 23日星期一 风向: 东北风 风级: <![CDATA[<3级]]> 高温: 高温 3℃ 低温: 低温 -5℃ 天气: 多云 -------------------------- 日期: 24日星期二 风向: 南风 风级: <![CDATA[<3级]]> 高温: 高温 1℃ 低温: 低温 -5℃ 天气: 阴 -------------------------- 日期: 25日星期三 风向: 北风 风级: <![CDATA[<3级]]> 高温: 高温 6℃ 低温: 低温 -5℃ 天气: 晴 -------------------------- ***********************************
=================绘制曲线 gisoracle================
# -*- coding: utf-8 -*- # 功能:查询城市天气 import requests, json, re from matplotlib import pyplot as plt # 获取城市代码 def getCityCode(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] return code else: return "000000000" # 获取城市天气信息 def getWeatherInfo(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 + ']不存在!' return weather # 打印天气信息 def printWeatherInfo(weather): for key in weather: print(key + weather[key]) # 获取未来气温 def getTemperatures(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 in range(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 + ']不存在!' return temperatures # 打印未来气温 def printTemperatures(temperatures): if '错误:' not in temperatures.keys(): for key in temperatures: print(key + ' 高温:' + str(temperatures[key][0]) + ' 低温:' + str(temperatures[key][1])) # 绘制未来气温折线图 def drawTemperatureLineChart(): temperatures = getTemperatures(city) if '错误:' not in temperatures.keys(): dates = [] highs = [] lows = [] for key in temperatures: 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()