本文的文字及圖片來源於網絡,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯系我們以作處理。
作者: 飛奔的帥帥
PS:如有需要Python學習資料的小伙伴可以加點擊下方鏈接自行獲取
http://note.youdao.com/noteshare?id=3054cce4add8a909e784ad934f956cef
本系統主要包括四個函數:
1、獲取天氣數據
-
輸入要查詢天氣的城市
-
利用urllib模塊向中華萬年歷天氣api接口請求天氣數據
-
利用gzip解壓獲取到的數據,並編碼utf-8
-
利用json轉化成python識別的數據,返回為天氣預報數據復雜形式的字典(字典中的字典)
2、輸出當天天氣數據
-
格式化輸出當天天氣,包括:天氣狀況,此時溫度,最高溫度、最低溫度,風級,風向等。
3,語音播報當天天氣
-
創建要輸出的語音文本(weather_forecast_txt)
-
利用百度的語音合成模塊AipSpeech,合成語音文件
-
利用playsound模塊播放語音
4、未來幾天溫度變化趨勢
-
創建未來幾天高低溫數據的字典
-
利用matplotlib模塊,圖形化溫度變化趨勢
5、代碼
1 #導入必要模塊 2 import urllib.parse 3 import urllib.request 4 import gzip 5 import json 6 import playsound 7 from aip import AipSpeech 8 import matplotlib.pyplot as plt 9 import re 10 #設置參數,圖片顯示中文字符,否則亂碼 11 plt.rcParams['font.sans-serif']=['SimHei'] 12 #定義獲取天氣數據函數 13 def Get_weather_data(): 14 print('------天氣查詢------') 15 city_name = input('請輸入要查詢的城市名稱:') 16 url = 'http://wthrcdn.etouch.cn/weather_mini?city=' + urllib.parse.quote(city_name) 17 weather_data = urllib.request.urlopen(url).read() 18 # 讀取網頁數據 19 weather_data = gzip.decompress(weather_data).decode('utf-8') 20 # #解壓網頁數據 21 weather_dict = json.loads(weather_data) 22 return weather_dict 23 #定義當天天氣輸出格式 24 def Show_weather(weather_data): 25 weather_dict = weather_data 26 if weather_dict.get('desc') == 'invilad-citykey': 27 print('你輸入的城市有誤或未收錄天氣,請重新輸入...') 28 elif weather_dict.get('desc') == 'OK': 29 forecast = weather_dict.get('data').get('forecast') 30 print('日期:', forecast[0].get('date')) 31 print('城市:', weather_dict.get('data').get('city')) 32 print('天氣:', forecast[0].get('type')) 33 print('溫度:', weather_dict.get('data').get('wendu') + '℃ ') 34 print('高溫:', forecast[0].get('high')) 35 print('低溫:', forecast[0].get('low')) 36 print('風級:', forecast[0].get('fengli').split('<')[2].split(']')[0]) 37 print('風向:', forecast[0].get('fengxiang')) 38 weather_forecast_txt = '您好,您所在的城市%s,' \ 39 '天氣%s,' \ 40 '當前溫度%s,' \ 41 '今天最高溫度%s,' \ 42 '最低溫度%s,' \ 43 '風級%s,' \ 44 '溫馨提示:%s' % \ 45 ( 46 weather_dict.get('data').get('city'), 47 forecast[0].get('type'), 48 weather_dict.get('data').get('wendu'), 49 forecast[0].get('high'), 50 forecast[0].get('low'), 51 forecast[0].get('fengli').split('<')[2].split(']')[0], 52 weather_dict.get('data').get('ganmao') 53 ) 54 return weather_forecast_txt,forecast 55 #定義語音播報今天天氣狀況 56 def Voice_broadcast(weather_forcast_txt): 57 weather_forecast_txt = weather_forcast_txt 58 APP_ID = 你的百度語音APP_ID 59 API_KEY = 你的百度語音API_KEY 60 SECRET_KEY = 你的百度語音SECRET_KEY 61 client = AipSpeech(APP_ID, API_KEY, SECRET_KEY) 62 print('語音提醒:', weather_forecast_txt) 63 #百度語音合成 64 result = client.synthesis(weather_forecast_txt, 'zh', 1, {'vol': 5}) 65 if not isinstance(result, dict): 66 with open('sound2.mp3', 'wb') as f: 67 f.write(result) 68 f.close() 69 #playsound模塊播放語音 70 playsound.playsound(r'C:\Users\ban\Desktop\bsy\sound2.mp3') 71 #未來四天天氣變化圖 72 def Future_weather_states(forecast): 73 future_forecast = forecast 74 dict={} 75 #獲取未來四天天氣狀況 76 for i in range(5): 77 data = [] 78 date=future_forecast[i]['date'] 79 date = int(re.findall('\d+',date)[0]) 80 data.append(int(re.findall('\d+',future_forecast[i]['high'])[0])) 81 data.append(int(re.findall('\d+', future_forecast[i]['low'])[0])) 82 data.append(future_forecast[i]['type']) 83 dict[date] = data 84 data_list = sorted(dict.items()) 85 date=[] 86 high_temperature = [] 87 low_temperature = [] 88 for each in data_list: 89 date.append(each[0]) 90 high_temperature.append(each[1][0]) 91 low_temperature.append(each[1][1]) 92 fig = plt.plot(date,high_temperature,'r',date,low_temperature,'b') 93 plt.xlabel('日期') 94 plt.ylabel('℃') 95 plt.legend(['高溫','低溫']) 96 plt.xticks(date) 97 plt.title('最近幾天溫度變化趨勢') 98 plt.show() 99 #主函數 100 if __name__=='__main__': 101 weather_data = Get_weather_data() 102 weather_forecast_txt, forecast = Show_weather(weather_data) 103 Future_weather_states(forecast) 104 Voice_broadcast(weather_forecast_txt)
6、最終效果