案例 (五)电视剧《沉默的真相》数据分析

作者: 王小鹏的随笔 | 来源:发表于2020-09-29 19:19 被阅读0次
image.png

代码及数据下载链接见文章末尾

一、导库

这里主要用的库有数据科学相关的numpy, pandas, 正则表达式re库,中文分词的jieba库,以及画图相关的pycharts库等。另外,为了能够在jupyter lab中直接画图,需要设置一下环境变量,声明画图的环境。

# 数据科学
import numpy as np
import pandas as pd
# 正则表达式
import re
import jieba
# 画图相关
from pyecharts.charts import Pie, Bar, Map, Line, Page
from pyecharts import options as opts
from pyecharts.globals import SymbolType, WarningType
WarningType.ShowWarning = False

pd.options.display.max_rows = 1000
# 设置画图环境,jupyter lab 中直接画图
from pyecharts.globals import CurrentConfig, NotebookType  
CurrentConfig.NOTEBOOK_TYPE = NotebookType.JUPYTER_LAB

import stylecloud
from IPython.display import Image # 用于在jupyter lab中显示本地图片
from collections import Counter

二、读取数据

2.1、读入数据:

直接读取的豆瓣的评论数据

df = pd.read_excel('../数据/沉默的真相豆瓣短评.xlsx')
print(df.shape) 
print(df.info())  
image.png

查看读入数据的前几条。

df.head()
image.png

2.2、查看重复值和空值

让我们来看看是否有重复值和空值。

# 查看重复值和空值
print(df.duplicated().sum())
print(df.isnull().sum())
image.png

结果没有重复值,空值,省去了数据的清洗这一步了。

三、数据预处理

3.1、删除列:

删除地址栏这一列,对我们分析没有起到作用。

# 删除列
df = df.drop('page_url', axis=1)

3.2、星级转换:

力荐,推荐,这些字符是纯中文的,没有明确的可量化比较的地方。所以将力荐,推荐,还行,较差,很差这些中文替换成星级的打分。

# 定义字典
def transform_rating(x):
    if x == '立荐':
        return '5星'
    elif x == '推荐':
        return '4星'
    elif x == '还行':
        return '3星'
    elif x == '较差':
        return '2星'
    elif x == '很差':
        return '1星'
    else:
        return '5星'  # 异常值使用众数替换

# apply函数
df['rating_num'] = df.rating_num.apply(transform_rating) 

查看星级的统计情况:

df.rating_num.value_counts() 
image.png

我们看到打5分的占到了绝大多数,说明这部电视剧的好评率还是蛮高的。

3.3、时间类型转换:

将时间转换到年月日,小时

comment_hour = df.comment_time.str.split(':').str[0]
comment_hour = comment_hour.value_counts().sort_index()
comment_hour[:5] 
image.png

3.4、分词处理:

我们需要从评论中提取关键有用信息,所以要先对评论进行分词处理。同时对停用词进行过滤,减少噪音的干扰。

# 定义分词函数

def get_cut_words(content_series):
    # 读入停用词表
    stop_words = [] 
    
    with open(r"../数据/stopword.txt", 'r', encoding='utf-8') as f:
        lines = f.readlines()
        for line in lines:
            stop_words.append(line.strip())

    # 添加关键词
    my_words = ['廖凡', '严良', '白宇', '江阳', '谭卓', '李静',
                '宁理', '张超', '黄尧', '张晓倩'
               ] 
    
    for i in my_words:
        jieba.add_word(i) 

    # 自定义停用词
    my_stop_words = ['真的', '这部', '这是', '一种']  
    stop_words.extend(my_stop_words)               

    # 分词
    word_num = jieba.lcut(content_series.str.cat(sep='。'), cut_all=False)

    # 条件筛选
    word_num_selected = [i for i in word_num if i not in stop_words and len(i) >= 2]
    
    return word_num_selected

四、可视化

4.1、星级分布情况:

让我们来具体看看星级的分布情况:

# 数据对
data_pair = [list(z) for z in zip(rating_num.index.tolist(), rating_num.values.tolist())]

# 绘制饼图
pie1 = Pie(init_opts=opts.InitOpts(width='1350px', height='750px'))
pie1.add('', data_pair=data_pair, radius=['35%', '60%']) 
pie1.set_global_opts(title_opts=opts.TitleOpts(title='总体评分分布'),  
                     legend_opts=opts.LegendOpts(orient='vertical', pos_top='15%', pos_right='2%'))
pie1.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}:{d}%"))
pie1.set_colors(['#FF7F0E', '#1F77B4', '#2CA02C', '#D62728', '#946C8B'])
pie1.load_javascript();  # 分号表示去除打印

load_javascript() 和 render_notebook() 在jupyter lab中换行执行,这样可以直接在jupyter lab中画图

pie1.render_notebook()
image.png

5星好评率达到了92.8%,口碑爆棚啊,有没有。

4.2、评论时间走势

接下来,我们看看评论的时间分布情况。

# 选取数据
x_data = [i.replace('2020-','') for i in comment_hour.index]
y_data = comment_hour.values.tolist()

# 折线图
line1 = Line(init_opts=opts.InitOpts(width='1350px', height='750px'))
line1.add_xaxis(x_data)
line1.add_yaxis('', y_data,
                areastyle_opts=opts.AreaStyleOpts(opacity=0.5),
                markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max")]),
                label_opts=opts.LabelOpts(is_show=False)
               ) 
line1.set_global_opts(title_opts=opts.TitleOpts(title='评论时间走势图'), 
                      xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate='60')),
                      visualmap_opts=opts.VisualMapOpts(max_=30))
line1.set_series_opts(linestyle_opts=opts.LineStyleOpts(width=3))
line1.load_javascript();

还是老规矩,换一行执行。

line1.render_notebook()
image.png

我们可以看到评论最多的时间集中在9月16日,这大概是《沉默的真相》刚上映没多久的时间。

4.3、绘制关键词词云

最后,我们看一下评论的词云绘制情况。

text = get_cut_words(content_series=df.short_comment)
# 绘制词云图
stylecloud.gen_stylecloud(text=' '.join(text), max_words=1000,
                          collocations=False,
                          font_path=r'C:\Windows\Fonts\msyh.ttc',
                          icon_name='fas fa-chart-pie',
                          size=653,
                          output_name='../数据/沉默的真相-豆瓣短评.png')

Image(filename='../数据/沉默的真相-豆瓣短评.png')
image.png

可以看到,最关键的几个词是江阳,是案情的受害者,演技说明大家对这部戏的普遍的演员演技讨论的很多,看来是非常认可演技啊。原著和还原,说的是这部戏从小说改编过来。


资料下载:
源码下载:源码下载
数据下载:数据下载
停用词下载:停用词下载

相关文章

网友评论

    本文标题:案例 (五)电视剧《沉默的真相》数据分析

    本文链接:https://www.haomeiwen.com/subject/vtoeuktx.html