菜鸟玩Python|制作天气查询软件

开发环境

  • Python3

  • PyQt5

  • requests

准备工作

首先要获取不同城市对应的天气代码,可以从 https://www.heweather.com/documents/city.html 网站下载 csv 文件(文末获取 csv 文件),拿到 csv 文件,我们首先要进行数据预处理工作。

import pandas as pd# 将下载好的文件命名为 'city_code.csv' file = pd.read_csv('city_code.csv')# 选取需要的两列信息 file = file.loc[:,['City_ID', 'City_CN']]# 读取前五行信息 file.head()

# 匹配 City_ID 中的数字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)# 将所得的字典数据存储为 txt 文件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'# 捕获 ConnectinError 异常    except requests.ConnectionError:        raise # 将获取的数据转换为 json 格式    try:        info_json = info.json()# 转换失败提示无法查询    except JSONDecodeError:        return '无法查询'

下面我们介绍下本文用到的控件方法:

# 将 textEdit 设置为只读模式 self.textEdit.setReadOnly(True)# 将鼠标焦点放在 lineEdit 编辑栏里 self.lineEdit.setFocus()# 获取 lineEdit 中的文本 city = self.lineEdit.text()# 设置文本 self.textEdit.setText(info)# 清空文本 self.lineEdit.clear()

为查询按钮设置快捷键:

def keyPressEvent(self, e):# 设置快捷键    if e.key() == Qt.Key_Return:        self.queryWeather()

最后,我们可以使用 pyinstaller -w weather.py 打包应用程序,但是要记得打包完,将 city_code.txt 复制到 dist/weather 文件夹下,否则程序无法运行。

登入/注册
卧槽~你还有脸回来
没有账号? 忘记密码?