python實現的、帶GUI界面電影票房數據可視化程序

代碼地址以下:<br>http://www.demodashi.com/demo/14588.htmlhtml

##詳細說明: Tushare是一個免費、開源的python財經數據接口包.主要實現對股票等金融數據從數據採集、清洗加工 到 數據存儲的過程,可以爲金融分析人員提供快速、整潔、和多樣的便於分析的數據。 完成本項目後,能夠進一步經過相似的方法實現股票數據的可視化操做. (代碼在python2.7或python3.6下均能正常運行,已在如下環境中進行過測試: python2.7 + tushare0.9.8 + matplotlib1.5 + pandas0.18 + numpy1.14 + wx2.8; python3.6 + tushare1.2 + matplotlib2.1 + pandas0.22 + numpy1.14 + wx4.0 )python

##準備工做: 1.安裝必要的第三方庫:app

pip install matplotlib
 pip install numpy
 pip install tushare
 pip install pandas
 pip install wxPython

##項目結構圖: 總體的項目結構十分簡單,一共四個腳本文件,一個是GUI界面腳本(BoxOfficeGui.py), 一個是繪圖腳本(plot_figure.py),一個是獲取臺北地區票房數據的 腳本(tw_boxoffice.py),一個是獲取美國票房數據的腳本(us_boxoffice.py)。 以下: 項目結構圖 (項目結構圖)python2.7

##實現過程的部分代碼展現 如下是程序的實現思路,以及步驟,實現步驟裏,附上了關鍵代碼,所有的代碼,請下載代碼後閱讀函數

  1. 在BoxOfficeGui.py中編寫用戶界面: 導入相關的庫:
import wx
import  wx.lib.dialogs
from collections import namedtuple
from plot_figure import plt_fig,plt_fig_month
from utility_template import layout_template
from tw_boxoffice import tw_fig
from us_boxoffice import us_fig

編寫界面:佈局

class MainWindow(wx.Frame):
    def __init__(self,parent,title):
        wx.Frame.__init__(self,parent,title=title,size=(600,-1))
        static_font = wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL)
        
        Size = namedtuple("Size",['x','y'])
        s = Size(100,50)

        """預約義參數"""
        self.fig = plt_fig()
        self.fig_month = plt_fig_month()
        
        self.tw_fig = tw_fig()
        self.us_fig = us_fig()
        
        b_labels = [
                    u'今日票房榜',
                      u'今日票房佔比',
                      u'總票房榜',
                      u'總票房佔比',
                      u'月票房榜',
                      u'月票房佔比',
                    u'臺北週末票房',
                    u'美國週末票房'
                        ]

        TipString = [ u'今日票房榜',
                      u'今日票房佔比',
                      u'總票房榜',
                      u'總票房佔比',
                      u'月票房榜',
                      u'月票房佔比',
                      u'臺北週末票房',
                      u'美國週末票房'
            ]
        funcs = [self.day_boxoffice,self.day_boxoffice_pre,
                 self.sum_boxoffice,self.sum_boxoffice_pre,
                 self.month_boxoffice,self.month_boxoffice_pre,
                 self.tw_boxoffice,self.us_boxoffice]
        
        """建立菜單欄"""
        filemenu = wx.Menu()
        menuExit = filemenu.Append(wx.ID_EXIT,"E&xit\tCtrl+Q","Tenminate the program 退出")

        menuBar = wx.MenuBar ()
        menuBar.Append(filemenu,"&File")
        self.SetMenuBar(menuBar)
        
        '''建立按鈕'''
        self.sizer0 = wx.FlexGridSizer(cols=2, hgap=4, vgap=2) 
        buttons = []
        for i,label in enumerate(b_labels):
            b = wx.Button(self, id = i,label = label,size = (1.5*s.x,s.y))
            buttons.append(b)
            self.sizer0.Add(b)      

        '''菜單綁定函數'''
        self.Bind(wx.EVT_MENU,self.OnExit,menuExit)

        '''設置各控件的顏色、字體屬性,綁定控件函數'''  
        for i,button in enumerate(buttons):
            button.SetForegroundColour('red')
            button.SetFont(static_font)
            button.SetToolTipString(TipString[i]) #wx2.8
##            button.SetToolTip(TipString[i])       #wx4.0
            button.Bind(wx.EVT_BUTTON,funcs[i])

        '''設置頁面佈局'''
        self.SetSizer(self.sizer0)
        self.SetAutoLayout(1)
        self.sizer0.Fit(self)
        
        self.CreateStatusBar()
        self.Show(True)

注意代碼中wx4.0版本與wx2.8版本的按鈕提示字符的設置方法是不同的. 界面以下: 程序界面 (GUI)測試

部分按鈕點擊後的效果以下: "今日票房榜"按鈕:繪製當日票房榜,以下圖, 內地日票房 (20181201內地票房)字體

"今日票房佔比"按鈕:獲取當天票房數據,並據此繪製當天票房百分佔比餅圖; 內地日票房佔比 (20181201內地票房佔比)網站

"月票房榜"按鈕:獲取指定月份的票房數據,並繪製該月票房榜(以「xxxx-xx"形式輸入指定月份),以下圖; 內地月票房 (2018-11月票房榜)ui

"月票房佔比"按鈕:獲取指定月份的票房數據,並繪製該月上映電影票房的百分比餅圖; 內地月票房佔比 (2018-11月票房佔比)

編寫控件的回調函數:

def day_boxoffice(self,evt):
        self.fig.day_boxoffice(title = u'本日票房',ylabel = u'票房\萬元')

    def sum_boxoffice(self,evt):
        self.fig.sum_boxoffice(title =u'本日影片累計票房',ylabel = u'累計票房\萬元')

    def month_boxoffice(self,evt):
        month = self.get_month()
        title = u'{m}票房'.format(m = month)
        self.fig_month.day_boxoffice(title,u'票房\萬元',month)

    def month_boxoffice_pre(self,evt):
        month = self.get_month()
        title = u'{m}票房佔比'.format(m = month)
        self.fig_month.day_boxoffice_pre(title,month)

    def tw_boxoffice(self,evt):
        self.tw_fig.weekend()

    def us_boxoffice(self,evt):
        self.us_fig.weekend()

2.編寫繪圖腳本(plot_figure.py): 導入相關的庫:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import tushare as ts
import time
import os

由於tushare庫提供了內地票房的接口,因此能夠經過tushare來獲取相關的票房 信息.

編寫獲取單日票房數據的函數:

class plt_fig():
    def __init__(self):
        tt = time.gmtime()
        self.today = str(tt[0]) + str(tt[1]) + str(tt[2])

    def get_data(self,*args):
        self.cd_dir()
        f0 = self.today+'.xlsx'
        try:
            d1 = pd.read_excel(f0)
        except IOError:
            d0 = ts.realtime_boxoffice()
            d0.to_excel(f0)
            d1 = pd.read_excel(f0)
        d2 = d1.Irank
        d3 = d1.BoxOffice
        d4 = d1.MovieName
        d5 = d1.sumBoxOffice
        return d2,d3,d4,d5
    
    def day_boxoffice(self,title = u'本日票房',ylabel = u'票房\萬元',*args):
        if len(args)>0:
            irank,box,name,sumbox = self.get_data(args[0])
        else:
            irank,box,name,sumbox = self.get_data()        
        self.plt_bar(irank,box,name,title,ylabel)
        
    def sum_boxoffice(self,title =u'本日影片累計票房',ylabel = u'累計票房\萬元'):
        irank,box,name,sumbox = self.get_data()
        self.plt_bar(irank,sumbox,name,title,ylabel)

編寫繪圖函數:

def plt_bar(self,xdata,ydata,xticks,title,ylabel):
        fig = plt.figure()
        ax = fig.add_subplot(111)
        bar_width = 0.65

        rect = ax.bar(xdata,ydata,bar_width,color = 'r')
        plt.xticks(xdata+bar_width/2,xticks)
        ax.set_title(title)
        ax.set_ylabel(ylabel)
        
        plt.grid()
        fig.autofmt_xdate()
        self.autolabel(ax,rect)
        plt.tight_layout()
        plt.show()

與之相似,能夠編寫一個獲取月度票房數據的類和函數, 類能夠繼承plt_fig,只需改寫其get_data函數便可. 程序到這裏已經能夠知足獲取內地票房數據並繪圖的需求了.

3.編寫獲取臺北,美國週末票房數據的腳本(tw_boxoffice.py): 由於tushare只提供了內地票房數據的接口,要獲取臺北等地 的票房數據,須要從其餘網站爬取.

pandas中的read_html函數能夠讀取網頁中的表格, 所以能夠直接用pandas讀取網頁的表格,稍做數據清洗後, 轉存爲本地的excel表格,程序再從中讀取數據而後繪圖.

導入相關的庫:

import pandas as pd

from plot_figure import plt_fig

獲取數據及數據清洗:

'''獲取臺北週末票房'''

class tw_fig(plt_fig):

    def table2excel(self,url):
        tbs = pd.read_html(url,header = 0,index_col = 0,skiprows = 0)
        df = tbs[1]
        df.columns = [u'MovieName',u'weekbox',u'sumbox',u'lastweek',u'weeknum',u'nouse']
        df.index.name = u'irank'

        df1 = df.fillna(method = 'bfill')
        df1 = df1.dropna(axis = 1,how = 'all')
        df1.weekbox = df1.weekbox.str.replace('$','')
        df1.sumbox = df1.sumbox.str.replace('$','')

        df1.sumbox = df1.sumbox.str.replace(',','')
        df1.weekbox = df1.weekbox.str.replace(',','')
    
        df1.sumbox = pd.to_numeric(df1.sumbox)
        df1.weekbox = pd.to_numeric(df1.weekbox)
    
        n = range(1,21)
        df2 = df1[df1.index.isin(n)]
        return df2

    def get_data(self,area,url):
        self.cd_dir()
        f0 = str(area)+'_'+self.today+'.xlsx'
        try:
            df = pd.read_excel(f0)
        except IOError:
            df = self.table2excel(url)
            df.to_excel(f0)
        irank = df.index
        weekbox = df.weekbox
        name = df.MovieName
        title = str(area)+self.today+'boxoffice'
        return irank,weekbox,name,title

與之相似,能夠編寫一個獲取美國票房數據的類和函數, 類能夠繼承tw_fig,只需改寫其weekend函數便可.

效果以下: 美國週末票房 (美國週末票房)python實現的、帶GUI界面電影票房數據可視化程序

代碼地址以下:<br>http://www.demodashi.com/demo/14588.html

注:本文著做權歸做者,由demo大師代發,拒絕轉載,轉載須要做者受權

相關文章
相關標籤/搜索