In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail how to realize the visualization of weather forecast by python. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Result display
Where:
The red line represents the highest temperature of the day, the blue line represents the minimum temperature, and the maximum temperature is marked with the weather of the day.
If you run the program at night, the points of the maximum and minimum temperatures will coincide, resulting in errors in crawling data.
Program code
Please refer to the notes for details.
#-*-coding: UTF-8-*-"" # @ Time: 2022-1-4 11 UTF-8 @ Author: distant Star # @ CSDN: https://blog.csdn.net/qq_44921056"""import chardetimport requestsfrom lxml import etreefrom fake_useragent import UserAgentimport pandas as pdfrom matplotlib import pyplot as plt# randomly generates request headers ua = UserAgent (verify_ssl=False) Path='D:/Pycharm/fake_useragent.json') # Random switching request header def random_ua (): headers = {"user-agent": ua.random} return headers# parsing page def res_text (url): res = requests.get (url=url) Headers=random_ua () res.encoding = chardet.detect (res.content) ['encoding'] response = res.text html = etree.HTML (response) return html# get page links for the next seven days and eight to fifteen days def get_url (url): html = res_text (url) url_7 =' http://www.weather.com.cn/' + html.xpath ('/ / * [@ id= "someDayNav"] / li [2] / a _) [2] / a _ Url_8_15# gets weather conditions for the next seven days def get_data_7 (url): html = res_text (url) list_s = html.xpath ('/ / * [@ id= "7d"] / ul/li') # get weather data list Date, Weather, Low, High = [] [] for i in range (len (list_s)): list_date = list_ s [I] .XPath ('. / h2/text ()') [0] # acquisition date For example, on the 4th (tomorrow) # print (list_data) list_weather = list_ s [I] .xpath ('. / p [1] / @ title') [0] # get the weather For example: light rain to sleet # print (list_weather) tem_low = list_ s [I] .XPath ('. / p [2] / i/text ()') # get the minimum temperature tem_high = list_ s [I] .xpath ('. / p [2] / span/text ()') # get the maximum temperature if tem_high = []: # encounter night conditions Screen out the highest temperature of the day tem_high = tem_low # when there is no maximum temperature Make the maximum temperature equal to the minimum temperature tem_low = int (tem_low [0]. Replace ('℃',')) # process the temperature data tem_high = int (tem_high [0]. Replace ('℃',')) # print (type (tem_high)) Date.append (list_date), Weather.append (list_weather), Low.append (tem_low) High.append (tem_high) excel = pd.DataFrame () # define a 2D list excel ['date'] = Date excel ['weather'] = Weather excel ['minimum temperature'] = Low excel ['maximum temperature'] = High # print (excel) return exceldef get_data_8_15 (url): html = res_text (url) list_s = html.xpath ('/ / * [ @ id= "15d"] / ul/li') Date Weather, Low, High = [], [] for i in range (len (list_s)): # data_s [0] is the date For example, on Tuesday (11th), data_s [1] is the weather condition, such as: cloudy to sunny, data_s [2] is the lowest temperature. For example: /-3 ℃ data_s = list_ s [I] .XPath ('. / span/text ()') # print (data_s) date = modify_str (data_s [0]) # get date weather = data_s [1] low = int (data_s [2]. Replace ('/','). Replace ('℃') '') high = int (list_ s [I] .XPath ('. / span/em/text ()') [0] .replace ('℃',')) # print (date, weather, low, high) Date.append (date), Weather.append (weather), Low.append (low), High.append (high) # print (Date, Weather, Low) High) excel = pd.DataFrame () # define a 2D list excel ['date'] = Date excel ['weather'] = Weather excel ['minimum temperature'] = Low excel ['maximum temperature'] = High # print (excel) return excel# change the date format from 8 to 15 days to be the same as the next 7 days def modify_str (date): date_1 = date.split ('(') Date_2 = date_1 [1] .replace (')' '') date_result = date_2 +'('+ date_1 [0] +') return date_result# implements data visualization def get_image (date, weather, high) Low): # used to display the Chinese label plt.rcParams ['font.sans-serif'] = [' SimHei'] # to normally display the negative sign plt.rcParams ['axes.unicode_minus'] = False # drawing graphics based on the data fig = plt.figure (dpi=128, figsize= (10,6) ax = fig.add_subplot (111l) plt.plot (date, high, cantilever, alpha=0.5) Marker='*') plt.plot (date, low, centering bluetooth, alpha=0.5, marker='o') # Color the middle part of the two broken lines in the chart plt.fill_between (date, high, low, facecolor='blue', alpha=0.2) # set the chart format plt.title ('Pizhou weather forecast for the last 15 days', fontsize=24) plt.xlabel ('date', fontsize=12) # draw oblique labels Avoid overlapping fig.autofmt_xdate () plt.ylabel ('temperature', fontsize=12) # Parameter tick setting plt.tick_params (axis='both', which='major', labelsize=10) # modify scale plt.xticks (date [:: 1]) # Mark points Mark the weather conditions of the day at the highest temperature for i in range (15): ax.annotate (weather [I], xy= (date [I], high [I]) # display picture plt.show () def main (): base_url = 'http://www.weather.com.cn/weather1d/101190805.shtml' url_7 Url_8_15 = get_url (base_url) data_1 = get_data_7 (url_7) data_2 = get_data_8_15 (url_8_15) data = pd.concat ([data_1, data_2], axis=0, ignore_index=True) # ignore_index=True to realize the splicing of two tables Do not keep the original index get_image (data ['date'], data ['weather'], data ['maximum temperature'], data ['minimum temperature']) if _ _ name__ = ='_ _ main__': main () this is the end of the article on "how to visualize the weather forecast by python". I hope the above content can be helpful to you, so that you can learn more knowledge. If you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.