欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python案例:查询城市天气并绘制最高气温与最低气温的折线图

程序员文章站 2022-07-14 16:51:36
...

1、编写源代码 - 查询城市天气.

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""
# 功能:查询城市天气
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)    
 
city = input('输入城市名:')
printWeatherInfo(getWeatherInfo(city))
printTemperatures(getTemperatures(city))
drawTemperatureLineChart()

运行结果:

Python案例:查询城市天气并绘制最高气温与最低气温的折线图