来源:Python高效编程
作者:flywind
以前,公众号分享了如何使用 PyQt5 制作猜数游戏和计时器,这一次,我们继续学习:如何使用 PyQt5 制作天气查询软件。
开发环境
准备工作
首先要获取不同城市对应的天气代码,可以从
https://www.heweather.com/documents/city.html
网站下载 csv 文件(文末获取 csv 文件),拿到 csv 文件,我们首先要进行数据预处理工作。
import pandas as pd
file = pd.read_csv('city_code.csv')
file = file.loc[:,['City_ID', 'City_CN']]
file.head()
def convert(x):
pat = re.compile('(\d+)')
return pat.search(x).group()
file['City_ID_map'] = file['City_ID'].map(convert)
def city2id(file):
code_dict = {}
key = 'City_CN'
value = 'City_ID_map'
for k, v in zip(file[key], file[value]):
code_dict[k] = v
return code_dict
code_dict = city2id(file)
import json
filename = 'city_code.txt'
with open(filename, 'w') as f:
json.dump(code_dict, f)
将字典存储为 txt 文件后,以后我们只需读取文件,再获取字典:
with open(filename, 'r') as f:
text = json.load(f)
如果不想费工夫处理这些数据,可以直接使用文末提供的 city_code.txt 文件。
Ui 设计
使用 Qt Designer,我们不难设计出以下界面:
如果不想设计这些界面,可以直接导入文末提供的 Ui_weather.py 文件。
主体逻辑:
我们这次使用的 api 接口为:'
http://wthrcdn.etouch.cn/weather_mini?citykey=
{code}',code 就是之前处理过的城市代码,比如常州的城市代码为:101191101。替换掉变量 code ,发送请求,网站返回给我们一段 json 格式的文件:
根据这段 json 语句,我们很容易提取需要的信息:
# 天气情况
data = info_json['data']
city = f"城市:{data['city']}\n"
today = data['forecast'][0]
date = f"日期:{today['date']}\n"
now = f"实时温度:{data['wendu']}度\n"
temperature = f"温度:{today['high']} {today['low']}\n"
fengxiang = f"风向:{today['fengxiang']}\n"
type = f"天气:{today['type']}\n"
tips = f"贴士:{data['ganmao']}\n"
当然,我们首先要使用 requests.get 方法,来获取这段 json 代码。
def query_weather(code):
html = f'http://wthrcdn.etouch.cn
/weather_mini?citykey={code}'
try:
info = requests.get(html)
info.encoding = 'utf-8'
except requests.ConnectionError:
raise
try:
info_json = info.json()
except JSONDecodeError:
return '无法查询'