Preface
The text and pictures of this article are from the Internet, only for learning and communication, not for any commercial purpose. The copyright belongs to the original author. If you have any questions, please contact us in time for handling.
Author: handsome and fast
PS: if you need Python learning materials, you can click the link below to get them by yourself
http://note.youdao.com/noteshare?id=3054cce4add8a909e784ad934f956cef
This system mainly includes four functions:
1. Get weather data
-
Enter the city to query for weather
-
Using urllib module to request weather data from weather api interface of Chinese calendar
-
Decompress the data obtained by gzip and code utf-8
-
Use json to convert the data recognized by python, and return to the dictionary (Dictionary in the dictionary) in the complex form of weather forecast data
2. Output weather data of the day
-
Format and output the weather of the day, including weather conditions, temperature, maximum temperature, minimum temperature, wind level, wind direction, etc.
3. Voice broadcast weather of the day
-
Create the voice text to output (weather? Forecast? Txt)
-
Using Baidu's speech synthesis module AipSpeech to synthesize speech files
-
Using playsound module to play voice
4. Temperature change trend in the next few days
-
Create a dictionary of high and low temperature data in the next few days
-
Use matplotlib module to figure the temperature change trend
5, code
1 #Import necessary modules 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 #Set the parameters, and the picture will display Chinese characters, otherwise, it will be garbled 11 plt.rcParams['font.sans-serif']=['SimHei'] 12 #Define get weather data function 13 def Get_weather_data(): 14 print('------Weather query------') 15 city_name = input('Please enter the city name to query:') 16 url = 'http://wthrcdn.etouch.cn/weather_mini?city=' + urllib.parse.quote(city_name) 17 weather_data = urllib.request.urlopen(url).read() 18 # Read web data 19 weather_data = gzip.decompress(weather_data).decode('utf-8') 20 # #Decompress web data 21 weather_dict = json.loads(weather_data) 22 return weather_dict 23 #Define the weather output format of the day 24 def Show_weather(weather_data): 25 weather_dict = weather_data 26 if weather_dict.get('desc') == 'invilad-citykey': 27 print('The city you entered is incorrect or the weather is not included, please re-enter...') 28 elif weather_dict.get('desc') == 'OK': 29 forecast = weather_dict.get('data').get('forecast') 30 print('Date:', forecast[0].get('date')) 31 print('City:', weather_dict.get('data').get('city')) 32 print('Weather:', forecast[0].get('type')) 33 print('Temperature:', weather_dict.get('data').get('wendu') + '℃ ') 34 print('High temperature:', forecast[0].get('high')) 35 print('Low temperature:', forecast[0].get('low')) 36 print('Wind scale:', forecast[0].get('fengli').split('<')[2].split(']')[0]) 37 print('Direction of wind:', forecast[0].get('fengxiang')) 38 weather_forecast_txt = 'Hello, your city%s,' \ 39 'weather%s,' \ 40 'Current temperature%s,' \ 41 'Today's highest temperature%s,' \ 42 'Minimum temperature%s,' \ 43 'Wind grade%s,' \ 44 'reminder:%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 #Define weather conditions for voice broadcast today 56 def Voice_broadcast(weather_forcast_txt): 57 weather_forecast_txt = weather_forcast_txt 58 APP_ID = Your Baidu voice APP_ID 59 API_KEY = Your Baidu voice API_KEY 60 SECRET_KEY = Your Baidu voice SECRET_KEY 61 client = AipSpeech(APP_ID, API_KEY, SECRET_KEY) 62 print('Voice alert:', weather_forecast_txt) 63 #Baidu speech synthesis 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 Module playing voice 70 playsound.playsound(r'C:\Users\ban\Desktop\bsy\sound2.mp3') 71 #Weather chart of the next four days 72 def Future_weather_states(forecast): 73 future_forecast = forecast 74 dict={} 75 #Get weather conditions for the next four days 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('date') 94 plt.ylabel('℃') 95 plt.legend(['high temperature','low temperature']) 96 plt.xticks(date) 97 plt.title('Trend of temperature change in recent days') 98 plt.show() 99 #Main function 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. Final effect
The above article of intelligent voice weather forecast implemented by python is the whole content shared by the editor, hoping to give you a reference