python实现的、带GUI界面电影票房数据可视化程序

代码地址如下:
http://www.demodashi.com/demo/14588.html

详细说明:

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
)

准备工作:

1.安装必要的第三方库:

 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)。
如下:
项目结构图
(项目结构图)

实现过程的部分代码展示

以下是程序的实现思路,以及步骤,实现步骤里,附上了关键代码,全部的代码,请下载代码后阅读

  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月票房榜)

"月票房占比"按钮:获取指定月份的票房数据,并绘制该月上映电影票房的百分比饼图;
内地月票房占比
(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界面电影票房数据可视化程序

代码地址如下:
http://www.demodashi.com/demo/14588.html

注:本文著作权归作者,由demo大师代发,拒绝转载,转载需要作者授权

猜你喜欢

转载自www.cnblogs.com/demodashi/p/10474113.html