发布时间:2019-09-03 08:58:37编辑:auto阅读(1640)
来源:Python高效编程
作者:flywind
以前,公众号分享了如何使用 PyQt5 制作猜数游戏和计时器,这一次,我们继续学习:如何使用 PyQt5 制作天气查询软件。
开发环境
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 文件后,以后我们只需读取文件,再获取字典:
获取更多技术知识点+v156 5219 9186,欢豆在线解答哦~
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']} " today = data['forecast'][0] date = f"日期:{today['date']} " now = f"实时温度:{data['wendu']}度 " temperature = f"温度:{today['high']} {today['low']} " fengxiang = f"风向:{today['fengxiang']} " type = f"天气:{today['type']} " tips = f"贴士:{data['ganmao']} "
当然,我们首先要使用 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 文件夹下,否则程序无法运行。
以上便是本文的全部内容了。
你想更深入了解学习Python知识体系,你可以看一下我们花费了一个多月整理了上百小时的几百个知识点体系内容:
【超全整理】《Python自动化全能开发从入门到精通》Python基础教程笔记
http://www.magedu.com/73198.html
希望大家有所帮助,祝愿大家学有所成。获取更多技术知识点+v156 5219 9186,欢豆在线解答哦~
上一篇: 如何找回断电、死机前未储存的Word,E
下一篇: Python权威指南的10个项目(1~5
48201
46945
37850
35152
29675
26337
25272
20293
19966
18424
36°
6058°
6768°
6253°
6230°
7349°
6176°
6304°
6778°
6787°