太強(qiáng)了,用Python+Excel制作天氣預(yù)報(bào)表!
大家好,我是村長~
今天給大家介紹一個(gè)Python+Excel的實(shí)戰(zhàn)項(xiàng)目,非常有趣。
主要使用xlwings和requests這兩個(gè)Python庫,以及Office的Excel。
xlwings處理表格,requests則是請求數(shù)據(jù)。
先從Excel中獲取城市信息,然后請求接口,獲取到天氣信息,再返回給Excel。
具體操作可以看下圖~

在城市欄輸入杭州,點(diǎn)擊查詢按鈕,表格的數(shù)據(jù)就會(huì)發(fā)生變化,的確是杭州的天氣預(yù)報(bào)。
① 數(shù)據(jù)獲取
既然是天氣預(yù)報(bào),那肯定是需要天氣數(shù)據(jù)的。
找了一圈國內(nèi)開放的天氣API接口,大多都是需要注冊,小F果斷放棄。
騰訊倒是有個(gè)不錯(cuò)的,可惜接口信息不太完整,沒有相應(yīng)的數(shù)據(jù)說明。
地址:https://tianqi.qq.com/
接口地址:https://wis.qq.com/weather/common

最終選擇了一個(gè)國外的天氣API接口。
地址:https://www.metaweather.com/zh/

并沒有提供國內(nèi)所有的城市,目前只有10個(gè)城市。
所以要想城市多一些,騰訊的天氣接口還是可以考慮的。
一共是有10種天氣狀態(tài),并且提供了相關(guān)的天氣狀態(tài)圖片,可以供我們使用。
圖片已經(jīng)下載下來了,需要的小伙伴可以文末獲取哦!

首先通過查詢,獲取城市的ID值。

然后根據(jù)ID值,再去獲取對應(yīng)的天氣信息。

相關(guān)名稱的中英文對照如下。
# 天氣--中英文名對照
weather = {
'Snow': '雪',
'Sleet': '雨夾雪',
'Hail': '冰雹',
'Thunderstorm': '雷陣雨',
'Heavy Rain': '大雨',
'Light Rain': '小雨',
'Showers': '陣雨',
'Heavy Cloud': '陰',
'Light Cloud': '多云',
'Clear': '晴'
}
# 城市--中英文名對照
citys = {
'北京': 'Beijing',
'成都': 'Chengdu',
'東莞': 'Dongguan',
'廣州': 'Guangzhou',
'杭州': 'Hangzhou',
'香港': 'Hong Kong',
'上海': 'Shanghai',
'深圳': 'Shenzhen',
'天津': 'Tianjin',
'武漢': 'Wuhan'
}
② 創(chuàng)建表格
安裝xlwings庫,并且使用命令行創(chuàng)建項(xiàng)目。
# 安裝xlwings
pip install xlwings -i https://mirror.baidu.com/pypi/simple/
# 命令行運(yùn)行
xlwings quickstart weatherapp --standalone
如此便會(huì)生成兩個(gè)文件,Python和Excel文件。

其中weatherapp.py的文件內(nèi)容如下。
import xlwings as xw
def main():
wb = xw.Book.caller()
sheet = wb.sheets[0]
if sheet["A1"].value == "Hello xlwings!":
sheet["A1"].value = "Bye xlwings!"
else:
sheet["A1"].value = "Hello xlwings!"
if __name__ == "__main__":
xw.Book("weatherapp.xlsm").set_mock_caller()
main()
而Excel是什么內(nèi)容也沒有的,打開時(shí)會(huì)提示是否啟用宏,選擇是。
然后需要將Excel的開發(fā)工具打開,后面會(huì)使用它插入一些元素。

上圖為Mac電腦的設(shè)置,Windows電腦設(shè)置起來也很簡單,具體可以百度。
通過點(diǎn)擊開發(fā)工具選項(xiàng),我們可以使用Excle的Visual Basic 編輯器(VBA),還能插入按鈕(查詢按鈕)。

然后我在表格中插入一個(gè)點(diǎn)擊按鈕。

選擇宏名稱為SampleCall,宏的位置為當(dāng)前工作簿。

點(diǎn)擊按鈕1,A1單元格出現(xiàn)內(nèi)容Hello xlwings!。

再次點(diǎn)擊,A1單元格內(nèi)容變?yōu)锽ye xlwings!。

也就意味著,修改weatherapp.py文件的代碼,即可實(shí)現(xiàn)Excel的交互操作。
下面對表格進(jìn)行頁面設(shè)計(jì),畢竟要讓表格好看起來。

設(shè)置表格的行高、列寬、背景色、固定文字內(nèi)容等信息。
將單元格C3名稱設(shè)置為city_name,插入6張?zhí)枅D片,排列在單元格C9~H9處,居中對齊,圖片也改名為no.1~no.6。
修改weatherapp.py文件代碼如下。
import json
from pathlib import Path
import requests
import xlwings as xw
# 天氣--中英文名對照
weather = {
'Snow': '雪',
'Sleet': '雨夾雪',
'Hail': '冰雹',
'Thunderstorm': '雷陣雨',
'Heavy Rain': '大雨',
'Light Rain': '小雨',
'Showers': '陣雨',
'Heavy Cloud': '陰',
'Light Cloud': '多云',
'Clear': '晴'
}
# 城市--中英文名對照
citys = {
'北京': 'Beijing',
'成都': 'Chengdu',
'東莞': 'Dongguan',
'廣州': 'Guangzhou',
'杭州': 'Hangzhou',
'香港': 'Hong Kong',
'上海': 'Shanghai',
'深圳': 'Shenzhen',
'天津': 'Tianjin',
'武漢': 'Wuhan'
}
def main():
# 通過runpython從excel中調(diào)用python函數(shù)
wb = xw.Book.caller()
sht = wb.sheets[0]
# 從Excel中讀取城市信息
city_name = citys[sht.range("city_name").value]
# 獲取城市的ID值, 即woeid
URL_CITY = f"https://www.metaweather.com/api/location/search/?query={city_name}"
response_city = requests.request("GET", URL_CITY)
city_title = json.loads(response_city.text)[0]["title"]
city_id = json.loads(response_city.text)[0]["woeid"]
# 獲取城市的天氣信息
URL_WEATHER = f"https://www.metaweather.com/api/location/{city_id}/"
response_weather = requests.request("GET", URL_WEATHER)
weather_data = json.loads(response_weather.text)["consolidated_weather"]
# 創(chuàng)建空列表, 存儲數(shù)據(jù)
min_temp = []
max_temp = []
weather_state_name = []
weather_state_abbr = []
applicable_date = []
# 處理數(shù)據(jù)
for index, day in enumerate(weather_data):
# 最低溫度
min_temp.append(weather_data[index]["min_temp"])
# 最高溫度
max_temp.append(weather_data[index]["max_temp"])
# 天氣情況
weather_state_name.append(weather[weather_data[index]["weather_state_name"]])
# 天氣情況縮寫
weather_state_abbr.append(weather_data[index]["weather_state_abbr"])
# 日期
applicable_date.append(weather_data[index]["applicable_date"])
# 將獲取到的值填充到Excel中
sht.range("C5").value = applicable_date
sht.range("C6").value = weather_state_name
sht.range("C7").value = max_temp
sht.range("C8").value = min_temp
sht.range("D3").value = city_title
# 創(chuàng)建列表
icon_names = ["no.1", "no.2", "no.3", "no.4", "no.5", "no.6"]
# 設(shè)置天氣圖片路徑
icon_path = Path(__file__).parent / "images"
# 將天氣情況與天氣圖片進(jìn)行匹配,更新表格
for icon, abbr in zip(icon_names, weather_state_abbr):
image_path = Path(icon_path, abbr + ".png")
sht.pictures.add(image_path, name=icon, update=True)
if __name__ == "__main__":
# 設(shè)置用于調(diào)試caller()的excel文件,可以直接在python里運(yùn)行
xw.Book("weatherapp.xlsm").set_mock_caller()
main()
此時(shí)我們打開Excel表格,在城市欄輸入10個(gè)城市中的一個(gè),然后點(diǎn)擊查詢按鈕,天氣就會(huì)更新。

接下來幾天,廣州都是大暴雨,廣州的小伙伴可要注意了~
好了,本期的分享就到此結(jié)束了,有興趣的小伙伴可以自行去實(shí)踐學(xué)習(xí)。
在公眾號回復(fù)「天氣」,即可獲取到本次使用到的代碼和數(shù)據(jù)。
終結(jié) Python 原生字典?這個(gè)庫要逆天改命了
10 分鐘入門 Python Rpc 實(shí)現(xiàn)
那些學(xué)計(jì)算機(jī)的女生后來都怎么樣了?
