1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > python制作气温分布图_Python案例:查询城市天气并绘制最高气温与最低气温的折线图...

python制作气温分布图_Python案例:查询城市天气并绘制最高气温与最低气温的折线图...

时间:2023-04-30 21:52:01

相关推荐

python制作气温分布图_Python案例:查询城市天气并绘制最高气温与最低气温的折线图...

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 = '/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./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./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()

运行结果:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。