Xiaobai Collection | Python implements weather query system

Insert picture description here
Today, I will teach you how to use Python to implement a weather query system. Xiaobai can also implement it. Let's try it.
The overall code:
import urllib.request
import gzip
import json
print('------weather query------')
def get_weather_data():
city_name = input('Please enter the name of the city you want to query:')
url1 ='http:
//wthrcdn.etouch.cn/weather_mini? city='+ urllib.parse.quote(city_name ) url2 ='http://wthrcdn.etouch.cn/weather_mini?citykey=101010100' #URL
1 only You need to enter the city name, and URL 2 needs to enter the city code
#print(url1)
weather_data = urllib.request.urlopen(url1).read() #Read
webpage data
weather_data = gzip.decompress(weather_data).decode('utf-8 ') #Unzip
webpage data
weather_dict = json.loads(weather_data) #Convert
json data into dict data
return weather_dict

def show_weather(weather_data):
weather_dict = weather_data #Convert
json data to dict data
if weather_dict.get('desc') = ='invilad-citykey':
print('The name of the city you entered is wrong, or the weather center is not included Your city')
elif weather_dict.get('desc') = ='OK':
forecast = weather_dict.get('data').get('forecast')
print('City:',weather_dict.get('data ').get('city'))
print('temperature:',weather_dict.get('data').get('wendu')+'℃')
print('a cold:',weather_dict.get('data ').get('ganmao'))
print('Wind direction:',forecast[0].get('fengxiang'))
print('Wind level:',forecast[0].get('fengli'))
print ('High temperature:',forecast[0].get('high'))
print('Low temperature:',forecast[0].get('low'))
print('weather:',forecast[0].get ('type'))
print('date:', forecast[0].get('date'))
print('*******************************')
four_day_forecast =input('Whether to display the weather for the next four days, yes /No:')
if four_day_forecast =='Yes' or'Y' or'y':
for i in range(1,5):
print('date:',forecast[i].get('date'))
print('Wind direction:',forecast[i].get('fengxiang'))
print('Wind level:',forecast[i].get('fengli'))
print('High temperature:',forecast[i] .get('high'))
print('Low temperature:',forecast[i].get('low'))
print('weather:',forecast[i].get('type'))
print('- -------------------------')
print('******************** ***************')

show_weather(get_weather_data())

The above is the specific implementation steps.
Part of the content of the article comes from the Internet, contact intrusion and deletion* The
article reference comes from http://http.taiyangruanjian.com/news/59271.html

Guess you like

Origin blog.csdn.net/zhimaHTTP/article/details/112346913