专栏名称: 马哥Linux运维
马哥linux致力于linux运维培训,连续多年排名第一,订阅者可免费获得学习机会和相关Linux独家实战资料!
目录
相关文章推荐
运维  ·  再见,CDN 巨头:Akamai 宣布 ... ·  2 天前  
51好读  ›  专栏  ›  马哥Linux运维

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

马哥Linux运维  · 公众号  · 运维  · 2019-06-12 17:00

正文

来源: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 文件后,以后我们只需读取文件,再获取字典:

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 '无法查询'






请到「今天看啥」查看全文