1. 程式人生 > >python取得當前的天氣資料

python取得當前的天氣資料

檢查天氣似乎相當簡單:開啟 Web 瀏覽器,點選位址列,輸入天氣網站的 URL(或搜尋一個,然後點選連結),等待頁面載入,跳過所有的廣告等。其實, 如果有一個程式,下載今後幾天的天氣預報,並以純文字打印出來,就可以跳過很多無聊的步驟。該程式利用 requests 模組,從網站下載資料。 總的來說,該程式將執行以下操作: • 從命令列讀取請求的位置。 • 從 OpenWeatherMap.org 下載 JSON 天氣資料。 • 將 JSON 資料字串轉換成 Python 的資料結構。 • 列印今天和未來兩天的天氣。 因此,程式碼需要完成以下任務: • 連線 sys.argv 中的字串,得到位置。 • 呼叫 requests.get(),下載天氣資料。 • 呼叫 json.loads(),將 JSON 資料轉換為 Python 資料結構。 • 列印天氣預報。 針對這個專案,開啟一個新的檔案編輯器視窗,並儲存為 quickWeather.py。  

從命令列引數獲取位置 該程式的輸入來自命令列。讓 quickWeather.py 看起來像這樣:

#! python3
# quickWeather.py - Prints the weather for a location from the command line.

import json, requests, sys

# Compute location from command line arguments.
if len(sys.argv) < 2:
	print('Usage: quickWeather.py location')
	sys.exit()
location = ' '.join(sys.argv[1:])

# TODO: Download the JSON data from OpenWeatherMap.org's API

# TODO: Load JSON data into a Python variable

在 Python 中,命令列引數儲存在 sys.argv 列表裡。 #!行和 import 語句之後,程式會檢查是否有多個命令列引數(回想一下, sys.argv 中至少有一個元素 sys.argv[0],它包含了 Python 指令碼的檔名)。如果該列表中只有一個元素,那麼使用者沒有在命令列中提供位置,程式向用戶提供“Usage(用法)”資訊,然後結束。命令列引數以空格分隔。命令列引數 San Francisco, CA 將使 sys.argv 中儲存['quickWeather.py', 'San', 'Francisco,', 'CA']。因此,呼叫 join()方法,將 sys.argv 中除第一個字串以外的字串連線起來。將連線的字串儲存在變數 location 中  

下載 JSON 資料 OpenWeatherMap.org 提供了 JSON 格式的實時天氣資訊。你的程式只需要下載頁面 http://api.openweathermap.org/data/2.5/forecast/daily?q=<Location>&cnt=3, 其中<Location>是想知道天氣的城市。將以下程式碼新增到 quickWeather.py 中。

#! python3
# quickWeather.py - Prints the weather for a location from the command line.

--snip--

# Download the JSON data from OpenWeatherMap.org's API
url = 'http://api.openweathermap.org/data/2.5/forecast/daily?q=%s&cnt=3' % (location)
response = requests.get(url)
response.raise_for_status()

# TODO: Load JSON data into a Python variable

我們從命令列引數中得到了 location。為了生成要訪問的網址,我們利用%s 佔位符,將 location 中儲存的字串插入 URL 字串的那個位置。結果儲存在 url 中,並將 url 傳入 requests.get()。 requests.get()呼叫返回一個 Response 物件,它可以通過呼叫 raise_for_status()來檢查錯誤。如果不發生異常,下載的文字將儲存在 response.text 中。

載入 JSON 資料並列印天氣 esponse.text 成員變數儲存了一個 JSON 格式資料的大字串。要將它轉換為Python 值,就呼叫 json.loads()函式。 JSON 資料會像這樣:

{'city': {'coord': {'lat': 37.7771, 'lon': -122.42},
	'country': 'United States of America',
	'id': '5391959',
	'name': 'San Francisco',
	'population': 0},
'cnt': 3,
'cod': '200',
'list': [{'clouds': 0,
	'deg': 233,
	'dt': 1402344000,
	'humidity': 58,
	'pressure': 1012.23,
	'speed': 1.96,
	'temp': {'day': 302.29,
		'eve': 296.46,
		'max': 302.29,
		'min': 289.77,
		'morn': 294.59,
		'night': 289.77},
	'weather': [{'description': 'sky is clear',
		'icon': '01d',
--snip--

可以將 weatherData 傳入 pprint.pprint,檢視這個資料。你可能要查詢 http://openweathermap.org/,找到關於這些欄位含義的文件。例如,線上文件會告訴你, 'day'後面的 302.29 是白天的開爾文溫度,而不是攝氏或華氏溫度。你想要的天氣描述在'main'和 'description'之後。為了整齊地打印出來,在quickWeather.py 中新增以下程式碼。

#! python3
# quickWeather.py - Prints the weather for a location from the command line.

--snip--

# Load JSON data into a Python variable
weatherData = json.loads(response.text)
# Print weather descriptions.
w = weatherData['list']
print('Current weather in %s: ' % (location))
print(w[0]['weather'][0]['main'], '-', w[0]['weather'][0]['description'])
print()
print('Tomorrow:')
print(w[1]['weather'][0]['main'], '-', w[1]['weather'][0]['description'])
print()
print('Day after tomorrow:')
print(w[2]['weather'][0]['main'], '-', w[2]['weather'][0]['description'])

注意,程式碼將 weatherData['list']儲存在變數 w 中,這將節省一些打字時間。可以用 w[0]、 w[1]和 w[2]來取得今天、明天和後天天氣的字典。這些字典都有'weather'鍵,其中包含一個列表值。你感興趣的是第一個列表項(一個巢狀的字典,包含幾個鍵), 下標是 0。這裡,我們打印出儲存在'main'和'description'鍵中的值,用連字元隔開。如果用命令列引數 quickWeather.py San Francisco, CA 執行這個程式,輸出看起來是這樣的:

Current weather in San Francisco, CA:
Clear - sky is clear

Tomorrow:
Clouds - few clouds

Day after tomorrow:
Clear - sky is clear

類似程式的想法 訪問氣象資料可以成為多種型別程式的基礎。你可以建立類似程式,完成以下任務: • 收集幾個露營地點或遠足路線的天氣預報,看看哪一個天氣最好。 • 如果需要將植物移到室內,安排一個程式定期檢查天氣併發送霜凍警報( • 從多個站點獲得氣象資料,同時顯示,或計算並顯示多個天氣預報的平均值。  

完整程式碼

#! python3
# quickWeather.py - Prints the weather for a location from the command line.

import json, requests, sys

# Compute location from command line arguments.
if len(sys.argv) < 2:
	print('Usage: quickWeather.py location')
	sys.exit()
location = ' '.join(sys.argv[1:])

# Download the JSON data from OpenWeatherMap.org's API
url = 'http://api.openweathermap.org/data/2.5/forecast/daily?q=%s&cnt=3' % (location)
response = requests.get(url)
response.raise_for_status()

# Load JSON data into a Python variable
weatherData = json.loads(response.text)
# Print weather descriptions.
w = weatherData['list']
print('Current weather in %s: ' % (location))
print(w[0]['weather'][0]['main'], '-', w[0]['weather'][0]['description'])
print()
print('Tomorrow:')
print(w[1]['weather'][0]['main'], '-', w[1]['weather'][0]['description'])
print()
print('Day after tomorrow:')
print(w[2]['weather'][0]['main'], '-', w[2]['weather'][0]['description'])