[Python實戰]Python製作天氣查詢軟體

在這裡插入圖片描述
以前,公眾號分享瞭如何使用 PyQt5 製作猜數遊戲和計時器,這一次,我們繼續學習:如何使用 PyQt5 製作天氣查詢軟體。
如需獲取原始碼和 exe 檔案,請在微信公眾號 Python高效程式設計
後臺回覆: 天氣
。
開發環境
- Python3
- PyQt5
- requests
準備工作
首先要獲取不同城市對應的天氣程式碼,可以從 https://www.heweather.com/documents/city.html 網站下載 csv 檔案(文末獲取 csv 檔案),拿到 csv 檔案,我們首先要進行資料預處理工作。
import pandas as pd # 將下載好的檔案命名為 'city_code.csv',並刪除 header 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 資料夾下,否則程式無法執行。
以上便是本文的全部內容了,更詳細的內容請見原始碼。如需獲取原始碼和 exe 檔案,請在微信公眾號 Python高效程式設計
後臺回覆: 天氣
。