[Python实战]Python制作天气查询软件


点击上方“Python爬虫与数据挖掘”,进行关注

回复“书籍”即可获赠Python从入门到进阶共10本电子书

开卷有益,多读书还是非常有帮助的。

640?wx_fmt=gif

以前,公众号分享了如何使用 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()as pd
# 将下载好的文件命名为 'city_code.csv'
file = pd.read_csv('city_code.csv')
# 选取需要的两列信息
file = file.loc[:,['City_ID', 'City_CN']]
# 读取前五行信息
file.head()

640?wx_fmt=jpeg

 
 
# 匹配 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 文件
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)'r') as f:
    text = json.load(f)

如果不想费工夫处理这些数据,可以直接使用文末提供的 city_code.txt 文件。

Ui 设计

使用 Qt Designer,我们不难设计出以下界面:

640?wx_fmt=jpeg

如果不想设计这些界面,可以直接导入文末提供的 Ui_weather.py 文件。

主体逻辑:

我们这次使用的 api 接口为:'http://wthrcdn.etouch.cn/weather_mini?citykey={code}',code 就是之前处理过的城市代码,比如常州的城市代码为:101191101。替换掉变量 code ,发送请求,网站返回给我们一段 json 格式的文件:

640?wx_fmt=jpeg

根据这段 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"
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 '无法查询'
# 模板网页
    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()
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()
# 设置快捷键
    if e.key() == Qt.Key_Return:
        self.queryWeather()

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

以上便是本文的全部内容了,更详细的内容请见源代码。如需获取源代码和 exe 文件,请在后台回复: 天气


------------------- End -------------------

往期精彩文章推荐:

640?wx_fmt=png

欢迎点赞,留言,转发,转载,感谢大家的相伴与支持

想加入Python学习群请在后台回复【入群

万水千山总是情,点个【在看】行不行

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值