python如何实现将天气预报可视化

python如何实现将天气预报可视化

这篇文章将为大家详细讲解有关python如何实现将天气预报可视化,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

结果展示

其中:

红线代表当天最高气温,蓝线代表最低气温,最高气温点上的标注为当天的天气情况。

如果使夜晚运行程序,则最高气温和最低气温的点会重合,使由爬取数据产生误差导致的。

程序代码

详细请看注释

#-*-coding:UTF-8-*-"""#@Time:2022/1/411:02#@Author:远方的星#@CSDN:https://blog.csdn.net/qq_44921056"""importchardetimportrequestsfromlxmlimportetreefromfake_useragentimportUserAgentimportpandasaspdfrommatplotlibimportpyplotasplt#随机产生请求头ua=UserAgent(verify_ssl=False,path='D:/Pycharm/fake_useragent.json')#随机切换请求头defrandom_ua():headers={"user-agent":ua.random}returnheaders#解析页面defres_text(url):res=requests.get(url=url,headers=random_ua())res.encoding=chardet.detect(res.content)['encoding']response=res.texthtml=etree.HTML(response)returnhtml#获得未来七天及八到十五天的页面链接defget_url(url):html=res_text(url)url_7='http://www.weather.com.cn/'+html.xpath('//*[@id="someDayNav"]/li[2]/a/@href')[0]url_8_15='http://www.weather.com.cn/'+html.xpath('//*[@id="someDayNav"]/li[3]/a/@href')[0]#print(url_7)#print(url_8_15)returnurl_7,url_8_15#获取未来七天的天气情况defget_data_7(url):html=res_text(url)list_s=html.xpath('//*[@id="7d"]/ul/li')#获取天气数据列表Date,Weather,Low,High=[],[],[],[]foriinrange(len(list_s)):list_date=list_s[i].xpath('./h2/text()')[0]#获取日期,如:4日(明天)#print(list_data)list_weather=list_s[i].xpath('./p[1]/@title')[0]#获取天气情况,如:小雨转雨夹雪#print(list_weather)tem_low=list_s[i].xpath('./p[2]/i/text()')#获取最低气温tem_high=list_s[i].xpath('./p[2]/span/text()')#获取最高气温iftem_high==[]:#遇到夜晚情况,筛掉当天的最高气温tem_high=tem_low#无最高气温时,使最高气温等于最低气温tem_low=int(tem_low[0].replace('℃',''))#将气温数据处理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()#定义一个二维列表excel['日期']=Dateexcel['天气']=Weatherexcel['最低气温']=Lowexcel['最高气温']=High#print(excel)returnexceldefget_data_8_15(url):html=res_text(url)list_s=html.xpath('//*[@id="15d"]/ul/li')Date,Weather,Low,High=[],[],[],[]foriinrange(len(list_s)):#data_s[0]是日期,如:周二(11日),data_s[1]是天气情况,如:阴转晴,data_s[2]是最低温度,如:/-3℃data_s=list_s[i].xpath('./span/text()')#print(data_s)date=modify_str(data_s[0])#获取日期情况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()#定义一个二维列表excel['日期']=Dateexcel['天气']=Weatherexcel['最低气温']=Lowexcel['最高气温']=High#print(excel)returnexcel#将8-15天日期格式改成与未来7天一致defmodify_str(date):date_1=date.split('(')date_2=date_1[1].replace(')','')date_result=date_2+'('+date_1[0]+')'returndate_result#实现数据可视化defget_image(date,weather,high,low):#用来正常显示中文标签plt.rcParams['font.sans-serif']=['SimHei']#用来正常显示负号plt.rcParams['axes.unicode_minus']=False#根据数据绘制图形fig=plt.figure(dpi=128,figsize=(10,6))ax=fig.add_subplot(111)plt.plot(date,high,c='red',alpha=0.5,marker='*')plt.plot(date,low,c='blue',alpha=0.5,marker='o')#给图表中两条折线中间的部分上色plt.fill_between(date,high,low,facecolor='blue',alpha=0.2)#设置图表格式plt.title('邳州近15天天气预报',fontsize=24)plt.xlabel('日期',fontsize=12)#绘制斜的标签,以免重叠fig.autofmt_xdate()plt.ylabel('气温',fontsize=12)#参数刻度线设置plt.tick_params(axis='both',which='major',labelsize=10)#修改刻度plt.xticks(date[::1])#对点进行标注,在最高气温点处标注当天的天气情况foriinrange(15):ax.annotate(weather[i],xy=(date[i],high[i]))#显示图片plt.show()defmain():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实现两张表拼接,不保留原索引get_image(data['日期'],data['天气'],data['最高气温'],data['最低气温'])if__name__=='__main__':main()

关于“python如何实现将天气预报可视化”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

发布于 2022-01-05 23:31:02
收藏
分享
海报
0 条评论
54
上一篇:SpringBoot怎么整合Springsecurity实现数据库登录及权限控制 下一篇:ecmascript是不是解释器
目录

    0 条评论

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码