欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python實(shí)戰(zhàn)之天氣預(yù)報(bào)系統(tǒng)的實(shí)現(xiàn)

 更新時(shí)間:2022年12月18日 09:45:24   作者:木木子學(xué)python  
本文主要和大家介紹了如何用代碼寫一款Python版天氣預(yù)報(bào)系統(tǒng),是Tkinter界面化的,還會(huì)制作溫度折線圖跟氣溫餅圖哦!感興趣的小伙伴可以嘗試一下

前言

鼎鼎大名的南方城市長(zhǎng)沙很早就入冬了,街上各種大衣,毛衣,棉衣齊齊出動(dòng)。

這段時(shí)間全國(guó)各地大風(fēng)嗚嗚地吹,很多地方斷崖式降溫。

雖然前幾天短暫的溫度回升,但肯定是為了今天的超級(jí)降溫,一大早的就開始狂風(fēng)四起。

周五早晨,終于體驗(yàn)了一把久違冷冷的冰雨在臉上胡亂的拍!昨天還有10幾度的天氣,今天就  只有2-3°了,真真是老天爺?shù)哪樒呤儈

廣東的朋友們,聽說你們哪兒最低溫度都是10幾度,我實(shí)名羨慕了——(要我說從哪兒聽說的,昨天跟刺激戰(zhàn)場(chǎng)打游戲的合作隊(duì)友哪兒聽說的。狠狠羨慕住了.jpg)

沒啥事兒,跟大家談一談天氣,哈哈哈,今天就給大家用代碼寫一款Python版天氣預(yù)報(bào)系統(tǒng),是Tkinter界面化的,還會(huì)制作溫度折線圖跟氣溫餅圖哦~一整個(gè)期待住了吧!

一、前期準(zhǔn)備

1)運(yùn)行環(huán)境

本文用到的環(huán)境如下——

Python3、Pycharm社區(qū)版,第三方模塊:tkinter、bs4(BeautifulSoup)、pandas、

prettytable、matplotlib、re。部分自帶的庫(kù)只要安裝完P(guān)ython就可以直接使用了

一般安裝:pip install +模塊名

鏡像源安裝:pip install -i https://pypi.douban.com/simple/+模塊名

有準(zhǔn)備一些數(shù)據(jù)源素材等這些大家可以用自己準(zhǔn)備的就可以了。

二、代碼展示

#coding:utf-8
from tkinter import *   
import re
from time import sleep
from urllib.request import urlopen
from bs4 import BeautifulSoup
import pandas
import prettytable
import matplotlib.pyplot as plt
from datetime import datetime
LOG_LINE_NUM = 0

class MY_GUI():
    def __init__(self,init_window_name):
        self.init_window_name = init_window_name

    #設(shè)置窗口
    def set_init_window(self):
        self.init_window_name.title("天氣預(yù)報(bào)")           #窗口名
        self.init_window_name.geometry('1000x500+200+50')
        #標(biāo)簽
        self.init_data_label = Label(self.init_window_name, text="輸入城市名")
        self.init_data_label.grid(row=0, column=0)
        self.result_data_label = Label(self.init_window_name, text="天氣預(yù)測(cè)結(jié)果")
        self.result_data_label.grid(row=0, column=12)
        #文本框
        self.init_data_Text = Text(self.init_window_name, width=20, height=1)  #城市名錄入框
        self.init_data_Text.grid(row=1, column=0, rowspan=2, columnspan=5)
        self.result_data_Text = Text(self.init_window_name, width=100, height=30)  #處理結(jié)果展示
        self.result_data_Text.grid(row=1, column=12, rowspan=10, columnspan=10)
        #按鈕
        self.str_trans_to_md7_button = Button(self.init_window_name, text="獲取天氣情況", bg="lightblue", width=10,command=self.str_trans_to_md7)  # 調(diào)用內(nèi)部方法  加()為直接調(diào)用
        self.str_trans_to_md7_button.grid(row=1, column=11)
        self.str_trans_to_img_button = Button(self.init_window_name, text="獲取天氣統(tǒng)計(jì)圖", bg="lightblue", width=10,command=self.str_trans_to_img)  # 調(diào)用內(nèi)部方法  加()為直接調(diào)用
        self.str_trans_to_img_button.grid(row=2, column=11)

    #功能函數(shù)
    def str_trans_to_md7(self):
        #儲(chǔ)存天氣情況的列表
        date,wea,tem_high,tem_low,wind_dire,wind_speed = [],[],[],[],[],[]
        #城市轉(zhuǎn)ID
        city_id = pandas.read_excel('city_id.xlsx')
        dict_c = city_id.set_index('City_CN').T.to_dict('list')
        city = self.init_data_Text.get(1.0,END).strip()
        test_id = dict_c[city]
        test_id.append("".join(filter(str.isdigit, test_id[0])))
        print('城市ID:',test_id[1])
        #爬七日天氣
        html_ID = "http://www.weather.com.cn/weather/"+test_id[1]+".shtml"
        html = urlopen(html_ID)
        soup = BeautifulSoup(html.read(),'html.parser')
        ag_links = soup.find_all("li", {"class": re.compile('sky skyid lv\d')})
        for ag in ag_links:
            date.append(ag.h1.get_text())
            wea.append(ag.p.get_text())
            tem_high.append(ag.span.get_text())
            win = re.findall('(?<= title=").*?(?=")', str(ag.find('p','win').find('em'))) #正則問題的處理,摘自csdn
            wind_dire.append( '-'.join(win))
        for i in range(7):
            tem_low.append(soup.select('.tem i')[i].get_text())
            wind_speed.append(soup.select('.win i')[i].get_text())
        #輸出圖表
        table_ = prettytable.PrettyTable()
        table_.field_names = ['日期','天氣', '最高溫度','最低溫度','風(fēng)向','風(fēng)力']
        for i in range(0,len(date)):
            table_.add_row([date[i], wea[i], tem_high[i],tem_low[i],wind_dire[i],wind_speed[i]])
        print(city,'七日天氣')
        print(table_)
        weafile=open("近七日天氣.txt","w+")
        weafile.write(city)
        weafile.write(test_id[1]+'/n')
        weafile.write(str(table_))
        weafile.close
        self.result_data_Text.delete(1.0,END)
        self.result_data_Text.insert(1.0,table_)
    def str_trans_to_img(self):#進(jìn)行統(tǒng)計(jì)圖的制作
        infopen = open('近七日天氣.txt', 'r', encoding='gbk')
        outopen = open('out1.txt', 'w', encoding='gbk')
        lines = infopen.readlines()
        for line in lines:
            if line.split():
                outopen.writelines(line)
            else:
                outopen.writelines("")
        infopen.close()
        outopen.close()
        with open("out1.txt", encoding='gbk') as fp_in:
            with open('out.txt', 'w', encoding='gbk') as fp_out:
                fp_out.writelines(line for i, line in enumerate(fp_in) if i > 2 and i<10)
        # clearnumber
        file = open("out.txt", "r")  # 以只讀模式讀取文件
        something=file.readlines()
        new=[]
        for x in something:
            first = x.strip('\n')
            second=first.split()
            while '|' in second:
                second.remove('|')
            new.append(second)

        dates, highs, lows = [], [], []
        for day in range(7):
            highs.append(int(new[day][2]))
            lows.append(int(new[day][3][0:2]))
            dates.append(new[day][0])

        fig = plt.figure(dpi=128, figsize=(10, 6))
        plt.plot(dates, highs, c='red', alpha=0.5) # alpha指定顏色透明度
        plt.plot(dates, lows, c='blue', alpha=0.5) # 注意dates和highs 以及l(fā)ows是匹配對(duì)應(yīng)的
        plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1) # facecolor指定了區(qū)域的顏色
        # 設(shè)置圖形格式
        plt.rcParams['font.sans-serif']=['SimHei'] #顯示中文標(biāo)簽
        plt.rcParams['axes.unicode_minus']=False
        plt.title("近七日溫度", fontsize=24)
        plt.xlabel('', fontsize=14)
        fig.autofmt_xdate() # 讓x軸標(biāo)簽斜著打印避免擁擠
        plt.ylabel('Temperature(℃)', fontsize=14)
        plt.tick_params(axis='both', which='major', labelsize=14)
        plt.savefig('溫度折線圖.jpg')
        plt.show()


        dic_wea = {}
        for i in range(0, 7):
            if new[i][1] in dic_wea.keys():
                dic_wea[new[i][1]] += 1
            else:
                dic_wea[new[i][1]] = 1
        plt.rcParams['font.sans-serif'] = ['SimHei']
        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('未來7天氣候分布餅圖')
        plt.savefig('氣候餅圖.jpg')
        plt.show()


        
        
def gui_start():
    init_window = Tk()              #實(shí)例化出一個(gè)父窗口

    ZMJ_PORTAL = MY_GUI(init_window)
    
    ZMJ_PORTAL.set_init_window()    # 設(shè)置根窗口默認(rèn)屬性

    init_window.mainloop()          #父窗口進(jìn)入事件循環(huán),可以理解為保持窗口運(yùn)行,否則界面不展示


gui_start()

三、效果展示

1)天氣預(yù)報(bào)系統(tǒng)

?2)溫度折線圖

3)氣溫餅圖

到此這篇關(guān)于Python實(shí)戰(zhàn)之天氣預(yù)報(bào)系統(tǒng)的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Python天氣預(yù)報(bào)系統(tǒng)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 如何對(duì)numpy?矩陣進(jìn)行通道間求均值

    如何對(duì)numpy?矩陣進(jìn)行通道間求均值

    這篇文章主要介紹了如何對(duì)numpy?矩陣進(jìn)行通道間求均值,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • 如何使用flask將模型部署為服務(wù)

    如何使用flask將模型部署為服務(wù)

    在某些場(chǎng)景下,我們需要將機(jī)器學(xué)習(xí)或者深度學(xué)習(xí)模型部署為服務(wù)給其它地方調(diào)用,本文接下來就講解使用python的flask部署服務(wù)的基本過程。
    2021-05-05
  • python中的annotate函數(shù)使用

    python中的annotate函數(shù)使用

    這篇文章主要介紹了python中的annotate函數(shù)使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • python用字節(jié)處理文件實(shí)例講解

    python用字節(jié)處理文件實(shí)例講解

    在本篇文章里小編給大家整理的是一篇關(guān)于python用字節(jié)處理文件實(shí)例講解內(nèi)容,有興趣的朋友們可以學(xué)習(xí)參考下。
    2021-04-04
  • python 生成器協(xié)程運(yùn)算實(shí)例

    python 生成器協(xié)程運(yùn)算實(shí)例

    下面小編就為大家?guī)硪黄猵ython 生成器協(xié)程運(yùn)算實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-09-09
  • python實(shí)現(xiàn)TCP文件接收發(fā)送

    python實(shí)現(xiàn)TCP文件接收發(fā)送

    這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)TCP文件接收發(fā)送,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • python結(jié)束程序運(yùn)行的四種方法

    python結(jié)束程序運(yùn)行的四種方法

    大家好,小編為大家解答python結(jié)束程序的代碼用什么符號(hào)的問題,很多人還不知道python如何結(jié)束程序運(yùn)行,文中通過代碼示例和圖文結(jié)合的方式介紹的非常詳細(xì),現(xiàn)在讓我們一起來看看吧
    2024-07-07
  • python中PIL安裝簡(jiǎn)單教程

    python中PIL安裝簡(jiǎn)單教程

    這篇文章主要為大家分享了python中PIL安裝簡(jiǎn)單教程,感興趣的小伙伴們可以參考一下
    2016-04-04
  • 用Python將GIF動(dòng)圖分解成多張靜態(tài)圖片

    用Python將GIF動(dòng)圖分解成多張靜態(tài)圖片

    今天給大家?guī)淼氖顷P(guān)于Python的相關(guān)知識(shí),文章圍繞著如何用Python將GIF動(dòng)圖分解成多張靜態(tài)圖片展開,文中有非常詳細(xì)的介紹,需要的朋友可以參考下
    2021-06-06
  • 對(duì)pycharm 修改程序運(yùn)行所需內(nèi)存詳解

    對(duì)pycharm 修改程序運(yùn)行所需內(nèi)存詳解

    今天小編就為大家分享一篇對(duì)pycharm 修改程序運(yùn)行所需內(nèi)存詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12

最新評(píng)論