python实现的电影票房数据可视化

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

##详细说明:

Tushare是一个免费、开源的python财经数据接口包.主要实现对股票等金融数据从数据采集、清洗加工 到 数据存储的过程,能够为金融分析人员提供快速、整洁、和多样的便于分析的数据。
完成本项目后,可以进一步通过类似的方法实现股票数据的可视化操作.
(代码在python2.7或python3.6下均能正常运行,已在以下环境中进行过测试:
python2.7 + tushare0.9.8 + matplotlib1.5.0 + pandas0.18.0 + numpy1.14.3;
python3.6 + tushare1.2 + matplotlib2.1.2 + pandas0.22.0 + numpy1.14.2
)

##准备工作:
1.安装必要的第三方库:

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

##项目结构:
整体的项目结构十分简单,一共四个脚本文件,一个是程序入口(BoxOffice_cli.py),
一个是绘图脚本(plot_figure.py),一个是获取台北地区票房数据的
脚本(tw_boxoffice.py),一个是获取美国票房数据的脚本(us_boxoffice.py)。
如下:
项目结构图

##实现过程的部分代码展示

  1. 在BoxOffice_cli.py编写程序命令说明:
"""
本程序可获取各地票房数据,
并将其可视化。
Usage:
Today boxoffice:
  python BoxOffice_cli.py
  
Sum boxoffice:
  python BoxOffice_cli.py -sum
  
Month boxoffice:
  python BoxOffice_cli.py -m month("xxxx-xx")
  
Taipei weekend boxoffice:
  python BoxOffice_cli.py -tw
  
US weekend boxoffice:
  python Boxoffice_cli.py -us
"""

导入相关的库:

import sys

from plot_figure import plt_fig,plt_fig_month 
from tw_boxoffice import tw_fig
from us_boxoffice import us_fig

编写程序入口:

class Main(object):
    def __init__(self):
        """预定义参数"""
        self.fig = plt_fig()
        self.fig_month = plt_fig_month()
        
        self.tw_fig = tw_fig()
        self.us_fig = us_fig()
        
    def day_boxoffice(self):
        self.fig.day_boxoffice(title = u'本日票房',ylabel = u'票房\万元')

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

    def month_boxoffice(self,month):
        self.fig_month.day_boxoffice(u'月份票房',u'票房\万元',month)       

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

    def us_boxoffice(self):
        self.us_fig.weekend()
        
if __name__ == '__main__':
    print(__doc__)
    main = Main()
    if len(sys.argv)==1:
        main.day_boxoffice()
        
    elif len(sys.argv)==2:
        action = sys.argv[1]
        if action =="-sum":
            main.sum_boxoffice()
        elif action =="-tw":
            main.tw_boxoffice()
        elif action =="-us":
            main.us_boxoffice()

    elif len(sys.argv)==3:
        month = sys.argv[2]
        main.month_boxoffice(month)
        
    else:
        print(__doc__)

运行效果如图:
cli

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实现的电影票房数据可视化

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

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

猜你喜欢

转载自blog.csdn.net/findhappy117/article/details/88147252