您好,登錄后才能下訂單哦!
這篇“Python怎么實現天氣預報系統”文章的知識點大部分人都不太理解,所以小編給大家總結了以下內容,內容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“Python怎么實現天氣預報系統”文章吧。
1)運行環境
本文用到的環境如下——
Python3、Pycharm社區版,第三方模塊:tkinter、bs4(BeautifulSoup)、pandas、
prettytable、matplotlib、re。部分自帶的庫只要安裝完Python就可以直接使用了
一般安裝:pip install +模塊名
鏡像源安裝:pip install -i https://pypi.douban.com/simple/+模塊名
#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 #設置窗口 def set_init_window(self): self.init_window_name.title("天氣預報") #窗口名 self.init_window_name.geometry('1000x500+200+50') #標簽 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="天氣預測結果") 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) #處理結果展示 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) # 調用內部方法 加()為直接調用 self.str_trans_to_md7_button.grid(row=1, column=11) self.str_trans_to_img_button = Button(self.init_window_name, text="獲取天氣統計圖", bg="lightblue", width=10,command=self.str_trans_to_img) # 調用內部方法 加()為直接調用 self.str_trans_to_img_button.grid(row=2, column=11) #功能函數 def str_trans_to_md7(self): #儲存天氣情況的列表 date,wea,tem_high,tem_low,wind_dire,wind_speed = [],[],[],[],[],[] #城市轉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.h2.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 = ['日期','天氣', '最高溫度','最低溫度','風向','風力'] 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):#進行統計圖的制作 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 以及lows是匹配對應的 plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1) # facecolor指定了區域的顏色 # 設置圖形格式 plt.rcParams['font.sans-serif']=['SimHei'] #顯示中文標簽 plt.rcParams['axes.unicode_minus']=False plt.title("近七日溫度", fontsize=24) plt.xlabel('', fontsize=14) fig.autofmt_xdate() # 讓x軸標簽斜著打印避免擁擠 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() #實例化出一個父窗口 ZMJ_PORTAL = MY_GUI(init_window) ZMJ_PORTAL.set_init_window() # 設置根窗口默認屬性 init_window.mainloop() #父窗口進入事件循環,可以理解為保持窗口運行,否則界面不展示 gui_start()
1)天氣預報系統
2)溫度折線圖
3)氣溫餅圖
以上就是關于“Python怎么實現天氣預報系統”這篇文章的內容,相信大家都有了一定的了解,希望小編分享的內容對大家有幫助,若想了解更多相關的知識內容,請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。