<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Python爬取天氣數(shù)據(jù)及可視化分析!

          共 18275字,需瀏覽 37分鐘

           ·

          2022-04-14 04:36

          ↑?關(guān)注 + 星標(biāo)?,每天學(xué)Python新技能

          后臺(tái)回復(fù)【大禮包】送你Python自學(xué)大禮包

          Python爬取天氣數(shù)據(jù)及可視化分析


          說(shuō)在前面

          • 天氣預(yù)報(bào)我們每天都會(huì)關(guān)注,我們可以根據(jù)未來(lái)的天氣增減衣物、安排出行,每天的氣溫、風(fēng)速風(fēng)向、相對(duì)濕度、空氣質(zhì)量等成為關(guān)注的焦點(diǎn)。本次使用python中requestsBeautifulSoup庫(kù)對(duì)中國(guó)天氣網(wǎng)當(dāng)天和未來(lái)14天的數(shù)據(jù)進(jìn)行爬取,保存為csv文件,之后用matplotlib、numpy、pandas對(duì)數(shù)據(jù)進(jìn)行可視化處理和分析,得到溫濕度度變化曲線、空氣質(zhì)量圖、風(fēng)向雷達(dá)圖等結(jié)果,為獲得未來(lái)天氣信息提供了有效方法。

          1.數(shù)據(jù)獲取

          請(qǐng)求網(wǎng)站鏈接

          • 首先查看中國(guó)天氣網(wǎng)的網(wǎng)址:http://www.weather.com.cn/weather/101280701.shtml這里就訪問(wèn)本地的天氣網(wǎng)址,如果想爬取不同的地區(qū)只需修改最后的101280701地區(qū)編號(hào)即可,前面的weather代表是7天的網(wǎng)頁(yè),weather1d代表當(dāng)天,weather15d代表未來(lái)14天。這里就主要訪問(wèn)7天和14天的中國(guó)天氣網(wǎng)。采用`requests.get()`方法,請(qǐng)求網(wǎng)頁(yè),如果成功訪問(wèn),則得到的是網(wǎng)頁(yè)的所有字符串文本。這就是請(qǐng)求過(guò)程。

            def getHTMLtext(url):     
            """請(qǐng)求獲得網(wǎng)頁(yè)內(nèi)容"""
            try:
            r = requests.get(url, timeout = 30)
            r.raise_for_status()
            r.encoding = r.apparent_encoding
            print("成功訪問(wèn)")
            return r.text
            except:
            print("訪問(wèn)錯(cuò)誤")
            return" "


          • 提取有用信息

            • 這里采用BeautifulSoup庫(kù)對(duì)剛剛獲取的字符串進(jìn)行數(shù)據(jù)提取,首先對(duì)網(wǎng)頁(yè)進(jìn)行檢查,找到需要獲取數(shù)據(jù)的標(biāo)簽:

            • 可以發(fā)現(xiàn)7天的數(shù)據(jù)信息在div標(biāo)簽中并且id=“7d”,并且日期、天氣、溫度、風(fēng)級(jí)等信息都在ul和li標(biāo)簽中,所以我們可以使用BeautifulSoup對(duì)獲取的網(wǎng)頁(yè)文本進(jìn)行查找div標(biāo)簽id=“7d”,找出他包含的所有的ul和li標(biāo)簽,之后提取標(biāo)簽中相應(yīng)的數(shù)據(jù)值,保存到對(duì)應(yīng)列表中。這里要注意一個(gè)細(xì)節(jié)就是有時(shí)日期沒(méi)有最高氣溫,對(duì)于沒(méi)有數(shù)據(jù)的情況要進(jìn)行判斷和處理。另外對(duì)于一些數(shù)據(jù)保存的格式也要提前進(jìn)行處理,比如溫度后面的攝氏度符號(hào),日期數(shù)字的提取,和風(fēng)級(jí)文字的提取,這需要用到字符查找及字符串切片處理。

              def get_content(html):
              """處理得到有用信息保存數(shù)據(jù)文件"""
              final = [] # 初始化一個(gè)列表保存數(shù)據(jù)
              bs = BeautifulSoup(html, "html.parser") # 創(chuàng)建BeautifulSoup對(duì)象
              body = bs.body
              data = body.find('div', {'id': '7d'}) # 找到div標(biāo)簽且id = 7d

              下面爬取當(dāng)天的數(shù)據(jù)


              data2 = body.find_all('div',{'class':'left-div'})
              text = data2[2].find('script').string
              text = text[text.index('=')+1 :-2] # 移除改var data=將其變?yōu)閖son數(shù)據(jù)
              jd = json.loads(text)
              dayone = jd['od']['od2'] # 找到當(dāng)天的數(shù)據(jù)
              final_day = [] # 存放當(dāng)天的數(shù)據(jù)
              count = 0
              for i in dayone:
              temp = []
              if count <=23:
              temp.append(i['od21']) # 添加時(shí)間
              temp.append(i['od22']) # 添加當(dāng)前時(shí)刻溫度
              temp.append(i['od24']) # 添加當(dāng)前時(shí)刻風(fēng)力方向
              temp.append(i['od25']) # 添加當(dāng)前時(shí)刻風(fēng)級(jí)
              temp.append(i['od26']) # 添加當(dāng)前時(shí)刻降水量
              temp.append(i['od27']) # 添加當(dāng)前時(shí)刻相對(duì)濕度
              temp.append(i['od28']) # 添加當(dāng)前時(shí)刻控制質(zhì)量
              #print(temp)
              final_day.append(temp)
              count = count +1


              下面爬取7天的數(shù)據(jù)


              ul = data.find('ul') # 找到所有的ul標(biāo)簽
              li = ul.find_all('li') # 找到左右的li標(biāo)簽
              i = 0 # 控制爬取的天數(shù)
              for day in li: # 遍歷找到的每一個(gè)li
              if i < 7 and i > 0:
              temp = [] # 臨時(shí)存放每天的數(shù)據(jù)
              date = day.find('h1').string # 得到日期
              date = date[0:date.index('日')] # 取出日期號(hào)
              temp.append(date)

              inf = day.find_all('p') # 找出li下面的p標(biāo)簽,提取第一個(gè)p標(biāo)簽的值,即天氣
              temp.append(inf[0].string)


                  tem_low = inf[1].find('i').string  	# 找到最低氣溫

              if inf[1].find('span') is None: # 天氣預(yù)報(bào)可能沒(méi)有最高氣溫
              tem_high = None
              else:
              tem_high = inf[1].find('span').string # 找到最高氣溫
              temp.append(tem_low[:-1])
              if tem_high[-1] == '℃':
              temp.append(tem_high[:-1])
              else:
              temp.append(tem_high)
              wind = inf[2].find_all('span') # 找到風(fēng)向
              for j in wind:
              temp.append(j['title'])
              wind_scale = inf[2].find('i').string # 找到風(fēng)級(jí)
              index1 = wind_scale.index('級(jí)')
              temp.append(int(wind_scale[index1-1:index1]))
              final.append(temp)
              i = i + 1

              return final_day,final


            • - ?同樣對(duì)于/weather15d:15天的信息,也做同樣的處理,這里經(jīng)過(guò)查看后發(fā)現(xiàn)他的15天網(wǎng)頁(yè)中只有8-14天,前面的1-7天在/weather中,這里就分別訪問(wèn)兩個(gè)網(wǎng)頁(yè)將爬取得到的數(shù)據(jù)進(jìn)行合并得到最終14天的數(shù)據(jù)。- ?前面是未來(lái)14天的數(shù)據(jù)爬取過(guò)程,對(duì)于當(dāng)天24小時(shí)的天氣信息數(shù)據(jù),經(jīng)過(guò)查找發(fā)現(xiàn)他是一個(gè)json數(shù)據(jù),可以通過(guò)

            • json.loads()
            • 方法獲取當(dāng)天的數(shù)據(jù),進(jìn)而對(duì)當(dāng)天的天氣信息進(jìn)行提取。



          保存csv文件

          • 前面將爬取的數(shù)據(jù)添加到列表中,這里引入csv庫(kù),利用f_csv.writerow(header)f_csv.writerows(data)方法,分別寫(xiě)入表頭和每一行的數(shù)據(jù),這里將1天和未來(lái)14天的數(shù)據(jù)分開(kāi)存儲(chǔ),分別保存為weather1.csvweather14.csv,下面是他們保存的表格圖:

          2.可視化分析

          當(dāng)天溫度變化曲線圖

          • 采用matplotlib中plt.plot()方法繪制出一天24小時(shí)的溫度變化曲線,并用plt.text()方法點(diǎn)出最高溫和最低溫,并畫(huà)出平均溫度線,下圖為溫度變化曲線圖:(代碼見(jiàn)附錄)

          分析可以發(fā)現(xiàn)這一天最高溫度為33℃,最低溫度為28℃,并且平均溫度在20.4℃左右,通過(guò)對(duì)時(shí)間分析,發(fā)現(xiàn)晝夜溫差5℃,低溫分布在凌晨,高溫分布在中午到下午的時(shí)間段。

          當(dāng)天相對(duì)濕度變化曲線圖

          • 采用matplotlib中plt.plot()方法繪制出一天24小時(shí)的濕度變化曲線,并畫(huà)出平均相對(duì)濕度線,下圖為濕度變化曲線圖:(代碼見(jiàn)附錄)

          分析可以發(fā)現(xiàn)這一天最高相對(duì)濕度為86%,最低相對(duì)濕度為58℃,并且平均相對(duì)濕度在75%左右,通過(guò)對(duì)時(shí)間分析,清晨的濕度比較大,而下午至黃昏濕度較小。

          溫濕度相關(guān)性分析圖

          • 經(jīng)過(guò)前面兩個(gè)圖的分析我們可以感覺(jué)到溫度和濕度之間是有關(guān)系的,為了更加清楚直觀地感受這種關(guān)系,使用plt.scatter()方法將溫度為橫坐標(biāo)、濕度為縱坐標(biāo),每個(gè)時(shí)刻的點(diǎn)在圖中點(diǎn)出來(lái),并且計(jì)算相關(guān)系數(shù),下圖為結(jié)果圖:

            分析可以發(fā)現(xiàn)一天的溫度和濕度具有強(qiáng)烈的相關(guān)性,他們呈負(fù)相關(guān),這就說(shuō)明他們時(shí)間是負(fù)相關(guān)關(guān)系,并且進(jìn)一步分析,當(dāng)溫度較低時(shí),空氣中水分含量較多,濕度自然較高,而溫度較高時(shí),水分蒸發(fā),空氣就比較干燥,濕度較低,符合平時(shí)氣候現(xiàn)象。
          • 空氣質(zhì)量指數(shù)柱狀圖

          • 空氣質(zhì)量指數(shù)AQI是定量描述空氣質(zhì)量狀況的指數(shù),其數(shù)值越大說(shuō)明空氣污染狀況越重,對(duì)人體健康的危害也就越大。一般將空氣質(zhì)量指數(shù)分為6個(gè)等級(jí),等級(jí)越高說(shuō)明污染越嚴(yán)重,下面使用plt.bar方法對(duì)一天24小時(shí)的空氣質(zhì)量進(jìn)行了柱狀圖繪制,并且根據(jù)6個(gè)等級(jí)的不同,相應(yīng)的柱狀圖的顏色也從淺到深,也表明污染逐步加重,更直觀的顯示污染情況,并且也將最高和最低的空氣質(zhì)量指數(shù)標(biāo)出,用虛線畫(huà)出平均的空氣質(zhì)量指數(shù),下圖是繪制結(jié)果圖:

            上面這張是南方珠海的控制質(zhì)量圖,可以看出空氣質(zhì)量指數(shù)最大也是在健康范圍,說(shuō)明珠海空氣非常好,分析可以發(fā)現(xiàn)這一天最高空氣質(zhì)量指數(shù)達(dá)到了35,最低則只有14,并且平均在25左右,通過(guò)時(shí)間也可以發(fā)現(xiàn),基本在清晨的時(shí)候是空氣最好的時(shí)候(4-9點(diǎn)),在下午是空氣污染最嚴(yán)重的時(shí)候,所以清晨一般可以去外面呼吸新鮮的空氣,那時(shí)污染最小。
          • - ?而下面這個(gè)空氣質(zhì)量圖是選取的北方的一個(gè)城市,可以看到這里的環(huán)境遠(yuǎn)遠(yuǎn)比不上珠海。


          • 風(fēng)向風(fēng)級(jí)雷達(dá)圖

          • 統(tǒng)計(jì)一天的風(fēng)力和風(fēng)向,由于風(fēng)力風(fēng)向使用極坐標(biāo)的方式展現(xiàn)較好,所以這里采用的是極坐標(biāo)的方式展現(xiàn)一天的風(fēng)力風(fēng)向圖,將圓分為8份,每一份代表一個(gè)風(fēng)向,半徑代表平均風(fēng)力,并且隨著風(fēng)級(jí)增高,藍(lán)色加深,最后結(jié)果如下所示:

            分析可以發(fā)現(xiàn)這一天西南風(fēng)最多,平均風(fēng)級(jí)達(dá)到了1.75級(jí),東北風(fēng)也有小部分1.0級(jí),其余空白方向無(wú)來(lái)風(fēng)。
          • 未來(lái)14天高低溫變化曲線圖

          • 統(tǒng)計(jì)未來(lái)14天的高低溫度變化,并繪制出他們的變化曲線圖,分別用虛線將他們的平均氣溫線繪制出來(lái),最后結(jié)果如下所示:

            分析可以發(fā)現(xiàn)未來(lái)14天高溫平均氣溫為30.5℃,溫度還是比較高,但是未來(lái)的第8天有降溫,需要做好降溫準(zhǔn)備,低溫前面處于平穩(wěn)趨勢(shì),等到第8天開(kāi)始下降,伴隨著高溫也下降,整體溫度下降,低溫平均在27℃左右。
          • 未來(lái)14天風(fēng)向風(fēng)級(jí)雷達(dá)圖

          • 統(tǒng)計(jì)未來(lái)14天的風(fēng)向和平均風(fēng)力,并和前面一樣采用極坐標(biāo)形式,將圓周分為8個(gè)部分,代表8個(gè)方向,顏色越深代表風(fēng)級(jí)越高,最后結(jié)果如下所示:

            分析可以發(fā)現(xiàn)未來(lái)14天東南風(fēng)、西南風(fēng)所占主要風(fēng)向,風(fēng)級(jí)最高達(dá)到了5級(jí),最低的西風(fēng)平均風(fēng)級(jí)也有3級(jí)。
          • 未來(lái)14天氣候分布餅圖

          • 統(tǒng)計(jì)未來(lái)14天的氣候,并求每個(gè)氣候的總天數(shù),最后將各個(gè)氣候的餅圖繪制出來(lái),結(jié)果如下所示:

            分析可以發(fā)現(xiàn)未來(lái)14天氣候基本是“雨”、“陰轉(zhuǎn)雨”和“陣雨”,下雨的天數(shù)較多,結(jié)合前面的氣溫分布圖可以看出在第8-9天氣溫高溫下降,可以推測(cè)當(dāng)天下雨,導(dǎo)致氣溫下降。
          • 3.結(jié)論

            • 1.首先根據(jù)爬取的溫濕度數(shù)據(jù)進(jìn)行的分析,溫度從早上低到中午高再到晚上低,濕度和溫度的趨勢(shì)相反,通過(guò)相關(guān)系數(shù)發(fā)現(xiàn)溫度和濕度有強(qiáng)烈的負(fù)相關(guān)關(guān)系,經(jīng)查閱資料發(fā)現(xiàn)因?yàn)殡S著溫度升高水蒸汽蒸發(fā)加劇,空氣中水分降低濕度降低。當(dāng)然,濕度同時(shí)受氣壓和雨水的影響,下雨濕度會(huì)明顯增高。- 2.經(jīng)查閱資料空氣質(zhì)量不僅跟工廠、汽車(chē)等排放的煙氣、廢氣等有關(guān),更為重要的是與氣象因素有關(guān)。由于晝夜溫差明顯變化,當(dāng)?shù)孛鏈囟雀哂诟呖諟囟葧r(shí),空氣上升,污染物易被帶到高空擴(kuò)散;當(dāng)?shù)孛鏈囟鹊陀谝欢ǜ叨鹊臏囟葧r(shí),天空形成逆溫層,它像一個(gè)大蓋子一樣壓在地面上空,使地表空氣中各種污染物不易擴(kuò)散。一般在晚間和清晨影響較大,而當(dāng)太陽(yáng)出來(lái)后,地面迅速升溫,逆溫層就會(huì)逐漸消散,于是污染空氣也就擴(kuò)散了。- 3.風(fēng)是由氣壓在水平方向分布的不均勻?qū)е碌摹oL(fēng)受大氣環(huán)流、地形、水域等不同因素的綜合影響,表現(xiàn)形式多種多樣,如季風(fēng)、地方性的海陸風(fēng)、山谷風(fēng)等,一天的風(fēng)向也有不同的變化,根據(jù)未來(lái)14天的風(fēng)向雷達(dá)圖可以發(fā)現(xiàn)未來(lái)所有風(fēng)向基本都有涉及,并且沒(méi)有特別的某個(gè)風(fēng)向,原因可能是近期沒(méi)有降水和氣文變化不大,導(dǎo)致風(fēng)向也沒(méi)有太大的變化規(guī)律。- 4.天氣是指某一個(gè)地區(qū)距離地表較近的大氣層在短時(shí)間內(nèi)的具體狀態(tài)。跟某瞬時(shí)內(nèi)大氣中各種氣象要素分布的綜合表現(xiàn)。根據(jù)未來(lái)14天的天氣和溫度變化可以大致推斷出某個(gè)時(shí)間的氣候,天氣和溫度之間也是有聯(lián)系的,

            4.代碼框架

            • 代碼主要分為weather.py:對(duì)中國(guó)天氣網(wǎng)進(jìn)行爬取天氣數(shù)據(jù)并保存csv文件;data1_analysis.py:對(duì)當(dāng)天的天氣信息進(jìn)行可視化處理;data14_analysis.py:對(duì)未來(lái)14天的天氣信息進(jìn)行可視化處理。下面是代碼的結(jié)構(gòu)圖:

            附源代碼

            weather.py

            #?weather.py
            import?requests
            from?bs4?import?BeautifulSoup
            import?csv
            import?json
            def?getHTMLtext(url):?????
            ?"""請(qǐng)求獲得網(wǎng)頁(yè)內(nèi)容"""
            ?try:?????????
            ??r?=?requests.get(url,?timeout?=?30)?????????
            ??r.raise_for_status()?????????
            ??r.encoding?=?r.apparent_encoding?????????
            ??print("成功訪問(wèn)")?????????
            ??return?r.text?????
            ?except:?????????
            ??print("訪問(wèn)錯(cuò)誤")?????????
            ??return"?"?

            def?get_content(html):
            ?"""處理得到有用信息保存數(shù)據(jù)文件"""
            ?final?=?[]??????????#?初始化一個(gè)列表保存數(shù)據(jù)
            ?bs?=?BeautifulSoup(html,?"html.parser")??#?創(chuàng)建BeautifulSoup對(duì)象
            ?body?=?bs.body
            ?data?=?body.find('div',?{'id':?'7d'})????#?找到div標(biāo)簽且id?=?7d
            ?#?下面爬取當(dāng)天的數(shù)據(jù)
            ?data2?=?body.find_all('div',{'class':'left-div'})
            ?text?=?data2[2].find('script').string??
            ?text?=?text[text.index('=')+1?:-2]???#?移除改var?data=將其變?yōu)閖son數(shù)據(jù)
            ?jd?=?json.loads(text)
            ?dayone?=?jd['od']['od2']?????#?找到當(dāng)天的數(shù)據(jù)
            ?final_day?=?[]???????????#?存放當(dāng)天的數(shù)據(jù)
            ?count?=?0
            ?for?i?in?dayone:
            ??temp?=?[]
            ??if?count?<=23:
            ???temp.append(i['od21'])?????#?添加時(shí)間
            ???temp.append(i['od22'])?????#?添加當(dāng)前時(shí)刻溫度
            ???temp.append(i['od24'])?????#?添加當(dāng)前時(shí)刻風(fēng)力方向
            ???temp.append(i['od25'])?????#?添加當(dāng)前時(shí)刻風(fēng)級(jí)
            ???temp.append(i['od26'])?????#?添加當(dāng)前時(shí)刻降水量
            ???temp.append(i['od27'])?????#?添加當(dāng)前時(shí)刻相對(duì)濕度
            ???temp.append(i['od28'])?????#?添加當(dāng)前時(shí)刻控制質(zhì)量
            ???#print(temp)
            ???final_day.append(temp)
            ??count?=?count?+1
            ?#?下面爬取7天的數(shù)據(jù)?
            ?ul?=?data.find('ul')??????#?找到所有的ul標(biāo)簽
            ?li?=?ul.find_all('li')??????#?找到左右的li標(biāo)簽
            ?i?=?0?????#?控制爬取的天數(shù)
            ?for?day?in?li:??????????#?遍歷找到的每一個(gè)li
            ?????if?i?<?7?and?i?>?0:
            ?????????temp?=?[]??????????#?臨時(shí)存放每天的數(shù)據(jù)
            ?????????date?=?day.find('h1').string?????#?得到日期
            ?????????date?=?date[0:date.index('日')]???#?取出日期號(hào)
            ?????????temp.append(date)????????????
            ?????????inf?=?day.find_all('p')??????#?找出li下面的p標(biāo)簽,提取第一個(gè)p標(biāo)簽的值,即天氣
            ?????????temp.append(inf[0].string)

            ?????????tem_low?=?inf[1].find('i').string???#?找到最低氣溫

            ?????????if?inf[1].find('span')?is?None:???#?天氣預(yù)報(bào)可能沒(méi)有最高氣溫
            ?????????????tem_high?=?None
            ?????????else:
            ?????????????tem_high?=?inf[1].find('span').string??#?找到最高氣溫
            ?????????temp.append(tem_low[:-1])
            ?????????if?tem_high[-1]?==?'℃':
            ??????????temp.append(tem_high[:-1])
            ?????????else:
            ??????????temp.append(tem_high)

            ?????????wind?=?inf[2].find_all('span')??#?找到風(fēng)向
            ?????????for?j?in?wind:
            ??????????temp.append(j['title'])

            ?????????wind_scale?=?inf[2].find('i').string?#?找到風(fēng)級(jí)
            ?????????index1?=?wind_scale.index('級(jí)')
            ?????????temp.append(int(wind_scale[index1-1:index1]))
            ?????????final.append(temp)
            ?????i?=?i?+?1
            ?return?final_day,final
            ?#print(final)????
            def?get_content2(html):
            ?"""處理得到有用信息保存數(shù)據(jù)文件"""
            ?final?=?[]????????????????#?初始化一個(gè)列表保存數(shù)據(jù)
            ?bs?=?BeautifulSoup(html,?"html.parser")????????#?創(chuàng)建BeautifulSoup對(duì)象
            ?body?=?bs.body
            ?data?=?body.find('div',?{'id':?'15d'})??????????#?找到div標(biāo)簽且id?=?15d
            ?ul?=?data.find('ul')????????????#?找到所有的ul標(biāo)簽
            ?li?=?ul.find_all('li')????????????#?找到左右的li標(biāo)簽
            ?final?=?[]
            ?i?=?0?????????????????#?控制爬取的天數(shù)
            ?for?day?in?li:???????????????#?遍歷找到的每一個(gè)li
            ?????if?i?<?8:
            ?????????temp?=?[]???????????????#?臨時(shí)存放每天的數(shù)據(jù)
            ?????????date?=?day.find('span',{'class':'time'}).string????#?得到日期
            ?????????date?=?date[date.index('(')+1:-2]????????#?取出日期號(hào)
            ?????????temp.append(date)??
            ?????????weather?=?day.find('span',{'class':'wea'}).string????#?找到天氣
            ?????????temp.append(weather)
            ?????????tem?=?day.find('span',{'class':'tem'}).text??????#?找到溫度
            ?????????temp.append(tem[tem.index('/')+1:-1])?????#?找到最低氣溫
            ?????????temp.append(tem[:tem.index('/')-1])??????#?找到最高氣溫
            ?????????wind?=?day.find('span',{'class':'wind'}).string????#?找到風(fēng)向
            ?????????if?'轉(zhuǎn)'?in?wind:???????????#?如果有風(fēng)向變化
            ??????????temp.append(wind[:wind.index('轉(zhuǎn)')])
            ??????????temp.append(wind[wind.index('轉(zhuǎn)')+1:])
            ?????????else:?????????????#?如果沒(méi)有風(fēng)向變化,前后風(fēng)向一致
            ??????????temp.append(wind)
            ??????????temp.append(wind)
            ?????????wind_scale?=?day.find('span',{'class':'wind1'}).string????#?找到風(fēng)級(jí)
            ?????????index1?=?wind_scale.index('級(jí)')
            ?????????temp.append(int(wind_scale[index1-1:index1]))
            ??????????
            ?????????final.append(temp)
            ?return?final

            def?write_to_csv(file_name,?data,?day=14):
            ?"""保存為csv文件"""
            ?with?open(file_name,?'a',?errors='ignore',?newline='')?as?f:
            ??if?day?==?14:
            ???header?=?['日期','天氣','最低氣溫','最高氣溫','風(fēng)向1','風(fēng)向2','風(fēng)級(jí)']
            ??else:
            ???header?=?['小時(shí)','溫度','風(fēng)力方向','風(fēng)級(jí)','降水量','相對(duì)濕度','空氣質(zhì)量']
            ??f_csv?=?csv.writer(f)
            ??f_csv.writerow(header)
            ??f_csv.writerows(data)

            def?main():
            ?"""主函數(shù)"""
            ?print("Weather?test")
            ?#?珠海
            ?url1?=?'http://www.weather.com.cn/weather/101280701.shtml'????#?7天天氣中國(guó)天氣網(wǎng)
            ?url2?=?'http://www.weather.com.cn/weather15d/101280701.shtml'?#?8-15天天氣中國(guó)天氣網(wǎng)
            ?
            ?html1?=?getHTMLtext(url1)
            ?data1,?data1_7?=?get_content(html1)??#?獲得1-7天和當(dāng)天的數(shù)據(jù)

            ?html2?=?getHTMLtext(url2)
            ?data8_14?=?get_content2(html2)???#?獲得8-14天數(shù)據(jù)
            ?data14?=?data1_7?+?data8_14
            ?#print(data)
            ?write_to_csv('weather14.csv',data14,14)?#?保存為csv文件
            ?write_to_csv('weather1.csv',data1,1)

            if?__name__?==?'__main__':
            ?main()


            data1_analysis.py:

            #?data1_analysis.py
            import?matplotlib.pyplot?as?plt
            import?numpy?as?np
            import?pandas?as?pd
            import?math
            def?tem_curve(data):
            ?"""溫度曲線繪制"""
            ?hour?=?list(data['小時(shí)'])
            ?tem?=?list(data['溫度'])
            ?for?i?in?range(0,24):
            ??if?math.isnan(tem[i])?==?True:
            ???tem[i]?=?tem[i-1]
            ?tem_ave?=?sum(tem)/24?????#?求平均溫度?
            ?tem_max?=?max(tem)????
            ?tem_max_hour?=?hour[tem.index(tem_max)]?#?求最高溫度
            ?tem_min?=?min(tem)
            ?tem_min_hour?=?hour[tem.index(tem_min)]?#?求最低溫度
            ?x?=?[]
            ?y?=?[]
            ?for?i?in?range(0,?24):
            ??x.append(i)
            ??y.append(tem[hour.index(i)])
            ?plt.figure(1)
            ?plt.plot(x,y,color='red',label='溫度')???????#?畫(huà)出溫度曲線
            ?plt.scatter(x,y,color='red')???#?點(diǎn)出每個(gè)時(shí)刻的溫度點(diǎn)
            ?plt.plot([0,?24],?[tem_ave,?tem_ave],?c='blue',?linestyle='--',label='平均溫度')??#?畫(huà)出平均溫度虛線
            ?plt.text(tem_max_hour+0.15,?tem_max+0.15,?str(tem_max),?ha='center',?va='bottom',?fontsize=10.5)??#?標(biāo)出最高溫度
            ?plt.text(tem_min_hour+0.15,?tem_min+0.15,?str(tem_min),?ha='center',?va='bottom',?fontsize=10.5)??#?標(biāo)出最低溫度
            ?plt.xticks(x)
            ?plt.legend()
            ?plt.title('一天溫度變化曲線圖')
            ?plt.xlabel('時(shí)間/h')
            ?plt.ylabel('攝氏度/℃')
            ?plt.show()

            def?hum_curve(data):
            ?"""相對(duì)濕度曲線繪制"""
            ?hour?=?list(data['小時(shí)'])
            ?hum?=?list(data['相對(duì)濕度'])
            ?for?i?in?range(0,24):
            ??if?math.isnan(hum[i])?==?True:
            ???hum[i]?=?hum[i-1]
            ?hum_ave?=?sum(hum)/24?????#?求平均相對(duì)濕度?
            ?hum_max?=?max(hum)????
            ?hum_max_hour?=?hour[hum.index(hum_max)]?#?求最高相對(duì)濕度
            ?hum_min?=?min(hum)
            ?hum_min_hour?=?hour[hum.index(hum_min)]?#?求最低相對(duì)濕度
            ?x?=?[]
            ?y?=?[]
            ?for?i?in?range(0,?24):
            ??x.append(i)
            ??y.append(hum[hour.index(i)])
            ?plt.figure(2)
            ?plt.plot(x,y,color='blue',label='相對(duì)濕度')???????#?畫(huà)出相對(duì)濕度曲線
            ?plt.scatter(x,y,color='blue')???#?點(diǎn)出每個(gè)時(shí)刻的相對(duì)濕度
            ?plt.plot([0,?24],?[hum_ave,?hum_ave],?c='red',?linestyle='--',label='平均相對(duì)濕度')??#?畫(huà)出平均相對(duì)濕度虛線
            ?plt.text(hum_max_hour+0.15,?hum_max+0.15,?str(hum_max),?ha='center',?va='bottom',?fontsize=10.5)??#?標(biāo)出最高相對(duì)濕度
            ?plt.text(hum_min_hour+0.15,?hum_min+0.15,?str(hum_min),?ha='center',?va='bottom',?fontsize=10.5)??#?標(biāo)出最低相對(duì)濕度
            ?plt.xticks(x)
            ?plt.legend()
            ?plt.title('一天相對(duì)濕度變化曲線圖')
            ?plt.xlabel('時(shí)間/h')
            ?plt.ylabel('百分比/%')
            ?plt.show()

            def?air_curve(data):
            ?"""空氣質(zhì)量曲線繪制"""
            ?hour?=?list(data['小時(shí)'])
            ?air?=?list(data['空氣質(zhì)量'])
            ?print(type(air[0]))
            ?for?i?in?range(0,24):
            ??if?math.isnan(air[i])?==?True:
            ???air[i]?=?air[i-1]
            ?air_ave?=?sum(air)/24?????#?求平均空氣質(zhì)量?
            ?air_max?=?max(air)????
            ?air_max_hour?=?hour[air.index(air_max)]?#?求最高空氣質(zhì)量
            ?air_min?=?min(air)
            ?air_min_hour?=?hour[air.index(air_min)]?#?求最低空氣質(zhì)量
            ?x?=?[]
            ?y?=?[]
            ?for?i?in?range(0,?24):
            ??x.append(i)
            ??y.append(air[hour.index(i)])
            ?plt.figure(3)
            ?
            ?for?i?in?range(0,24):
            ??if?y[i]?<=?50:
            ???plt.bar(x[i],y[i],color='lightgreen',width=0.7)??#?1等級(jí)
            ??elif?y[i]?<=?100:
            ???plt.bar(x[i],y[i],color='wheat',width=0.7)???#?2等級(jí)
            ??elif?y[i]?<=?150:
            ???plt.bar(x[i],y[i],color='orange',width=0.7)???#?3等級(jí)
            ??elif?y[i]?<=?200:
            ???plt.bar(x[i],y[i],color='orangered',width=0.7)??#?4等級(jí)
            ??elif?y[i]?<=?300:
            ???plt.bar(x[i],y[i],color='darkviolet',width=0.7)??#?5等級(jí)
            ??elif?y[i]?>?300:
            ???plt.bar(x[i],y[i],color='maroon',width=0.7)???#?6等級(jí)
            ?plt.plot([0,?24],?[air_ave,?air_ave],?c='black',?linestyle='--')??#?畫(huà)出平均空氣質(zhì)量虛線
            ?plt.text(air_max_hour+0.15,?air_max+0.15,?str(air_max),?ha='center',?va='bottom',?fontsize=10.5)??#?標(biāo)出最高空氣質(zhì)量
            ?plt.text(air_min_hour+0.15,?air_min+0.15,?str(air_min),?ha='center',?va='bottom',?fontsize=10.5)??#?標(biāo)出最低空氣質(zhì)量
            ?plt.xticks(x)
            ?plt.title('一天空氣質(zhì)量變化曲線圖')
            ?plt.xlabel('時(shí)間/h')
            ?plt.ylabel('空氣質(zhì)量指數(shù)AQI')
            ?plt.show()

            def?wind_radar(data):
            ?"""風(fēng)向雷達(dá)圖"""
            ?wind?=?list(data['風(fēng)力方向'])
            ?wind_speed?=?list(data['風(fēng)級(jí)'])
            ?for?i?in?range(0,24):
            ??if?wind[i]?==?"北風(fēng)":
            ???wind[i]?=?90
            ??elif?wind[i]?==?"南風(fēng)":
            ???wind[i]?=?270
            ??elif?wind[i]?==?"西風(fēng)":
            ???wind[i]?=?180
            ??elif?wind[i]?==?"東風(fēng)":
            ???wind[i]?=?360
            ??elif?wind[i]?==?"東北風(fēng)":
            ???wind[i]?=?45
            ??elif?wind[i]?==?"西北風(fēng)":
            ???wind[i]?=?135
            ??elif?wind[i]?==?"西南風(fēng)":
            ???wind[i]?=?225
            ??elif?wind[i]?==?"東南風(fēng)":
            ???wind[i]?=?315
            ?degs?=?np.arange(45,361,45)
            ?temp?=?[]
            ?for?deg?in?degs:
            ??speed?=?[]
            ??#?獲取?wind_deg?在指定范圍的風(fēng)速平均值數(shù)據(jù)
            ??for?i?in?range(0,24):
            ???if?wind[i]?==?deg:
            ????speed.append(wind_speed[i])
            ??if?len(speed)?==?0:
            ???temp.append(0)
            ??else:
            ???temp.append(sum(speed)/len(speed))
            ?print(temp)
            ?N?=?8
            ?theta?=?np.arange(0.+np.pi/8,2*np.pi+np.pi/8,2*np.pi/8)
            ?#?數(shù)據(jù)極徑
            ?radii?=?np.array(temp)
            ?#?繪制極區(qū)圖坐標(biāo)系
            ?plt.axes(polar=True)
            ?#?定義每個(gè)扇區(qū)的RGB值(R,G,B),x越大,對(duì)應(yīng)的顏色越接近藍(lán)色
            ?colors?=?[(1-x/max(temp),?1-x/max(temp),0.6)?for?x?in?radii]
            ?plt.bar(theta,radii,width=(2*np.pi/N),bottom=0.0,color=colors)
            ?plt.title('一天風(fēng)級(jí)圖',x=0.2,fontsize=20)
            ?plt.show()

            def?calc_corr(a,?b):
            ?"""計(jì)算相關(guān)系數(shù)"""
            ?a_avg?=?sum(a)/len(a)
            ?b_avg?=?sum(b)/len(b)
            ?cov_ab?=?sum([(x?-?a_avg)*(y?-?b_avg)?for?x,y?in?zip(a,?b)])
            ?sq?=?math.sqrt(sum([(x?-?a_avg)**2?for?x?in?a])*sum([(x?-?b_avg)**2?for?x?in?b]))?
            ?corr_factor?=?cov_ab/sq
            ?return?corr_factor


            def?corr_tem_hum(data):
            ?"""溫濕度相關(guān)性分析"""
            ?tem?=?data['溫度']
            ?hum?=?data['相對(duì)濕度']
            ?plt.scatter(tem,hum,color='blue')
            ?plt.title("溫濕度相關(guān)性分析圖")
            ?plt.xlabel("溫度/℃")
            ?plt.ylabel("相對(duì)濕度/%")
            ?plt.text(20,40,"相關(guān)系數(shù)為:"+str(calc_corr(tem,hum)),fontdict={'size':'10','color':'red'})
            ?plt.show()
            ?print("相關(guān)系數(shù)為:"+str(calc_corr(tem,hum)))

            def?main():
            ?plt.rcParams['font.sans-serif']=['SimHei']?#?解決中文顯示問(wèn)題
            ?plt.rcParams['axes.unicode_minus']?=?False??#?解決負(fù)號(hào)顯示問(wèn)題
            ?data1?=?pd.read_csv('weather1.csv',encoding='gb2312')
            ?print(data1)
            ?tem_curve(data1)
            ?hum_curve(data1)
            ?air_curve(data1)
            ?wind_radar(data1)
            ?corr_tem_hum(data1)
            if?__name__?==?'__main__':
            ?main()

            data14_analysis.py:

            #?data14_analysis.py
            import?matplotlib.pyplot?as?plt
            import?numpy?as?np
            import?pandas?as?pd
            import?math

            def?tem_curve(data):
            ?"""溫度曲線繪制"""
            ?date?=?list(data['日期'])
            ?tem_low?=?list(data['最低氣溫'])
            ?tem_high?=?list(data['最高氣溫'])
            ?for?i?in?range(0,14):
            ??if?math.isnan(tem_low[i])?==?True:
            ???tem_low[i]?=?tem_low[i-1]
            ??if?math.isnan(tem_high[i])?==?True:
            ???tem_high[i]?=?tem_high[i-1]

            ?tem_high_ave?=?sum(tem_high)/14?????#?求平均高溫?
            ?tem_low_ave?=?sum(tem_low)/14?????#?求平均低溫?
            ?
            ?tem_max?=?max(tem_high)????
            ?tem_max_date?=?tem_high.index(tem_max)???#?求最高溫度
            ?tem_min?=?min(tem_low)
            ?tem_min_date?=?tem_low.index(tem_min)???#?求最低溫度

            ?x?=?range(1,15)
            ?plt.figure(1)
            ?plt.plot(x,tem_high,color='red',label='高溫')????#?畫(huà)出高溫度曲線
            ?plt.scatter(x,tem_high,color='red')?????#?點(diǎn)出每個(gè)時(shí)刻的溫度點(diǎn)
            ?plt.plot(x,tem_low,color='blue',label='低溫')????#?畫(huà)出低溫度曲線
            ?plt.scatter(x,tem_low,color='blue')?????#?點(diǎn)出每個(gè)時(shí)刻的溫度點(diǎn)
            ?
            ?plt.plot([1,?15],?[tem_high_ave,?tem_high_ave],?c='black',?linestyle='--')??#?畫(huà)出平均溫度虛線
            ?plt.plot([1,?15],?[tem_low_ave,?tem_low_ave],?c='black',?linestyle='--')??#?畫(huà)出平均溫度虛線
            ?plt.legend()
            ?plt.text(tem_max_date+0.15,?tem_max+0.15,?str(tem_max),?ha='center',?va='bottom',?fontsize=10.5)??#?標(biāo)出最高溫度
            ?plt.text(tem_min_date+0.15,?tem_min+0.15,?str(tem_min),?ha='center',?va='bottom',?fontsize=10.5)??#?標(biāo)出最低溫度
            ?plt.xticks(x)
            ?plt.title('未來(lái)14天高溫低溫變化曲線圖')
            ?plt.xlabel('未來(lái)天數(shù)/天')
            ?plt.ylabel('攝氏度/℃')
            ?plt.show()
            def?change_wind(wind):
            ?"""改變風(fēng)向"""
            ?for?i?in?range(0,14):
            ??if?wind[i]?==?"北風(fēng)":
            ???wind[i]?=?90
            ??elif?wind[i]?==?"南風(fēng)":
            ???wind[i]?=?270
            ??elif?wind[i]?==?"西風(fēng)":
            ???wind[i]?=?180
            ??elif?wind[i]?==?"東風(fēng)":
            ???wind[i]?=?360
            ??elif?wind[i]?==?"東北風(fēng)":
            ???wind[i]?=?45
            ??elif?wind[i]?==?"西北風(fēng)":
            ???wind[i]?=?135
            ??elif?wind[i]?==?"西南風(fēng)":
            ???wind[i]?=?225
            ??elif?wind[i]?==?"東南風(fēng)":
            ???wind[i]?=?315
            ?return?wind


            def?wind_radar(data):
            ?"""風(fēng)向雷達(dá)圖"""
            ?wind1?=?list(data['風(fēng)向1'])
            ?wind2?=?list(data['風(fēng)向2'])
            ?wind_speed?=?list(data['風(fēng)級(jí)'])
            ?wind1?=?change_wind(wind1)
            ?wind2?=?change_wind(wind2)
            ?
            ?degs?=?np.arange(45,361,45)
            ?temp?=?[]
            ?for?deg?in?degs:
            ??speed?=?[]
            ??#?獲取?wind_deg?在指定范圍的風(fēng)速平均值數(shù)據(jù)
            ??for?i?in?range(0,14):
            ???if?wind1[i]?==?deg:
            ????speed.append(wind_speed[i])
            ???if?wind2[i]?==?deg:
            ????speed.append(wind_speed[i])
            ??if?len(speed)?==?0:
            ???temp.append(0)
            ??else:
            ???temp.append(sum(speed)/len(speed))
            ?print(temp)
            ?N?=?8
            ?theta?=?np.arange(0.+np.pi/8,2*np.pi+np.pi/8,2*np.pi/8)
            ?#?數(shù)據(jù)極徑
            ?radii?=?np.array(temp)
            ?#?繪制極區(qū)圖坐標(biāo)系
            ?plt.axes(polar=True)
            ?#?定義每個(gè)扇區(qū)的RGB值(R,G,B),x越大,對(duì)應(yīng)的顏色越接近藍(lán)色
            ?colors?=?[(1-x/max(temp),?1-x/max(temp),0.6)?for?x?in?radii]
            ?plt.bar(theta,radii,width=(2*np.pi/N),bottom=0.0,color=colors)
            ?plt.title('未來(lái)14天風(fēng)級(jí)圖',x=0.2,fontsize=20)
            ?plt.show()

            def?weather_pie(data):
            ?"""繪制天氣餅圖"""
            ?weather?=?list(data['天氣'])
            ?dic_wea?=?{?}
            ?for?i?in?range(0,14):
            ??if?weather[i]?in?dic_wea.keys():
            ???dic_wea[weather[i]]?+=?1
            ??else:
            ???dic_wea[weather[i]]?=?1
            ?print(dic_wea)
            ?explode=[0.01]*len(dic_wea.keys())
            ?color?=?['lightskyblue','silver','yellow','salmon','grey','lime','gold','red','green','pink']
            ?plt.pie(dic_wea.values(),explode=explode,labels=dic_wea.keys(),autopct='%1.1f%%',colors=color)
            ?plt.title('未來(lái)14天氣候分布餅圖')
            ?plt.show()

            def?main():
            ?plt.rcParams['font.sans-serif']=['SimHei']?#?解決中文顯示問(wèn)題
            ?plt.rcParams['axes.unicode_minus']?=?False??#?解決負(fù)號(hào)顯示問(wèn)題
            ?data14?=?pd.read_csv('weather14.csv',encoding='gb2312')
            ?print(data14)
            ?tem_curve(data14)
            ?wind_radar(data14)
            ?weather_pie(data14)

            if?__name__?==?'__main__':
            ?main()





          1. 上海疫情究竟怎么樣了?

          2. 國(guó)內(nèi)爬蟲(chóng)開(kāi)發(fā)人員的未來(lái)

          3. xdm,外包能干嗎?


          瀏覽 26
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  色老板综合 | 黄色大片一级片 | 中文字幕免费视频在线观看 | 91久久久18久久久 | 人人草人人舔 |