获取当地天气
作者:互联网
获取当地天气
更改Bam文件染色体名字
本文作者:Sunny-King
发布时间:2022-08-27 16:37:34 星期六
本文链接:https://www.cnblogs.com/Sunny-King/p/Python-weather.html
最近实现一个小工具,其中涵盖了天气的功能,把自己的实现过程以及如何使用记录如下。
Gittee:https://gitee.com/wanliwumai/weather.git
♥特别注意:不要频繁调用该API,避免增加服务器的负载
一、安装所需模块
import os
import re
import json
import requests
import argparse
from datetime import datetime
二、代码介绍
1、根据城市名称获取城市ID
已经将大部分城市与城市对应的代码存放于script/weather_city.json,首先根据输入的名字获取ID
def get_id(city):
"""
根据城市名获取id
:param city: city_names
:return: city_id
"""
root_path = os.path.split(os.path.realpath(__file__))[0]
with open(os.path.join(root_path, 'weather_city.json'), 'r', encoding='utf8') as fp:
city_dict = json.load(fp)
if city in city_dict:
return city_dict[city]
else:
print('Can not find the city: {}'.format(city))
return city_dict['北京']
2、调用API返回当前城市的天气
调用API返回天气的字典
def get_weather(city):
"""
调用API返回当前天气
:param city: city_name
:return:
"""
city_id = get_id(city)
weather_web = 'http://wthrcdn.etouch.cn/weather_mini?citykey='
request = requests.get('{}{}'.format(weather_web, city_id))
weatherinfo = request.json()
return weatherinfo
3、定制个性化输出
该部分额外加入时间判断,在早上7:00之前不进行输出,在晚上20:00之后加入第二天的天气情况。可进行个性化定制
def info_edit(info):
"""
规范化输出天气信息
:param info: 天气的字典
:return:
"""
flag = get_flag()
if flag == 0:
return None
today = datetime.today().strftime("%Y-%m-%d")
city = info['data']['city']
low = info['data']['forecast'][0]['low']
high = info['data']['forecast'][0]['high']
fengxiang = info['data']['forecast'][0]['fengxiang']
fengli = re.findall('<!\[CDATA\[(\d+级)\]\]>', info['data']['forecast'][0]['fengli'])[0]
wendu = info['data']['wendu']
string = info['data']['ganmao']
line = "今天是: {}\n{}: {}~{}\n{}\t{}\n实时温度: {} ℃\n{}\n".format(
today, city, low, high, fengxiang, fengli, wendu, string)
if flag == 1:
low_t = info['data']['forecast'][1]['low']
high_t = info['data']['forecast'][1]['high']
fengxiang_t = info['data']['forecast'][1]['fengxiang']
fengli_t = re.findall('<!\[CDATA\[(\d+级)\]\]>', info['data']['forecast'][1]['fengli'])[0]
line += "明天: {}~{}\n{}\t{}\n".format(low_t, high_t, fengxiang_t, fengli_t)
return line
三、使用方法
直接下载代码安装所需模块后即可使用
git clone https://gitee.com/wanliwumai/weather.git
python weather/script/weather.py -c "北京"
可根据自己的需求设计个性化的输出。
标签:info,city,return,当地,天气,forecast,获取,weather,data 来源: https://www.cnblogs.com/Sunny-King/p/Python-weather.html