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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM