数据可视化-天气预报

在简单读完Python入门与实践项目2(数据可视化)之后,简单的做的一个天气显示。可以说和书上的差不多,用来熟悉一下。

  • 数据接口使用的是聚合数据上的API
  • key需要自己申请,这里就删除了
  • 可以查询5天之内的天气信息
import requests
import pygal

url = 'http://apis.juhe.cn/simpleWeather/query'
city = input("请输入查询城市:")
# 传递URL参数字典
payload = {
    'city': city,
    'key': ''
}
response = requests.post(url, params=payload)
# 查看状态码
print("Response Code:", response.status_code)

# 处理相关信息
result_dict = response.json()
if result_dict:
    try:
        error_code = result_dict['error_code']
        if error_code == 0:
            # 温度
            temperature = result_dict['result']['realtime']['temperature']
            # 湿度
            humidity = result_dict['result']['realtime']['humidity']
            # 天气情况
            info = result_dict['result']['realtime']['info']
            # 风向
            direct = result_dict['result']['realtime']['direct']
            # 风力
            power = result_dict['result']['realtime']['power']
            # 空气质量指数
            aqi = result_dict['result']['realtime']['aqi']
            # 获取预测信息
            futures = result_dict['result']['future']
            dates, min_plot_dicts, max_plot_dicts = [], [], []
            for future in futures:
                date = future['date']
                min_plot_dict = {
                    "value":int(future['temperature'].strip('℃').split('/', 1)[0]),
                    "label": future['weather'],
                }
                max_plot_dict={
                    "value" : int(future['temperature'].strip('℃').split('/', 1)[-1]),
                    "label" : future['weather'],
                }
                dates.append(date)
                min_plot_dicts.append(min_plot_dict)
                max_plot_dicts.append(max_plot_dict)
            print("温度:%s\n湿度:%s\n天气:%s\n风向:%s\n风力:%s\n空气质量:%s" % (
                temperature, humidity, info, direct, power, aqi))
            print('dates:', dates)

        else:
            print("请求失败:%s %s" % (result_dict['error_code'], result_dict["reason"]))
    except Exception:
        print(Exception.__repr__())
    else:
        line_cart = pygal.Line()
        line_cart.title = 'Future 5 days temperature'
        line_cart.x_labels = dates
        line_cart.add('min', min_plot_dicts)
        line_cart.add('max', max_plot_dicts)
        line_cart.render_to_file('temperature.svg')
else:
    # 由于网络异常等原因,无法获取返回内容,请求异常
    print('请求失败')

显示的图形:
数据可视化-天气预报_第1张图片

你可能感兴趣的:(Python,python,可视化)