大家好,我是J哥。
最近《八佰》这部电影比较火,上映仅15天就已斩获22亿票房。对于沉寂了半年、影院上座率仍限定在50%的电影市场而言,这样的成绩出人意料。
从猫眼电影官网可以看到,《八佰》获得了9.2分的高口碑。一向好奇的J哥产生了一些疑惑,这些人到底在评论些啥?哪些地方的人评论最多?针对不同演员角色的评论内容有什么不同?
于是,J哥用Python采集了《八佰》18万条观众影评并做可视化分析,数据采集区间为2020年8月21日9点至2020年8月30日24点。公众号后台回复
八佰
可获取本文完整数据集和代码。
猫眼电影是简单的动态网页,数据格式为json,通过解析接口的方式即可轻松获取。如果您对动态网页爬虫感兴趣,可查看J哥往期原创文章
《实战|Python轻松实现动态网页爬虫(附详细源码)》
。本文不做赘述,仅提供核心代码:
def parse_page(html):
data = json.loads(html)['cmts'] # 将str转换为json
#print(data)
comments = []
for item in data:
comment = {
'id': item['id'],
'nickName': item['nickName'],
'cityName': item['cityName'] if 'cityName' in item else '', # 处理cityName不存在的情况
'content': item['content'].replace('\n', ' ', 10), # 处理评论内容换行的情况
'score': item['score'],
'startTime': item['startTime']
comments.append(comment)
return comments
except Exception as e:
读取影评数据
import pandas as pd
import numpy as np
data=[]
with open('comments.txt', 'r',encoding='utf-8-sig') as f_input:
for line in f_input:
data.append(list(line.strip().split(',')))
转为DataFrame并添加列名
df = pd.DataFrame(data).iloc[:, 0:6]
df.columns = ['观众ID','观众昵称','城市','评论内容','评分','评论时间']
删除重复记录和缺失值
df = df.drop_duplicates()
df = df.dropna()
预览并保存
df.sample(5)
df.to_csv("八佰.csv",index=False,encoding="utf_8_sig")
数据可视化
导入相关库
import jieba
import re
import matplotlib.pyplot as plt
from pyecharts.charts import *
from pyecharts import options as opts
from pyecharts.globals import ThemeType
import stylecloud
from IPython.display import Image
整体评论词云
data = pd.read_csv("八佰.csv")
data['评论内容'] = data['评论内容'].astype('str')
# 定义分词函数
def get_cut_words(content_series):
# 读入停用词表
stop_words = []
with open("stop_words.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
# 绘制词云图
text1 = get_cut_words(content_series=data['评论内容'])
stylecloud.gen_stylecloud(text=' '.join(text1), max_words=500,
collocations=False,
font_path='字酷堂清楷体.ttf',
icon_name='fas fa-square',
size=653,
#palette='matplotlib.Inferno_9',
output_name='./1.png')
Image(filename='./1.png')
对18万条影评内容进行分词,并将频率最高的500个词抽离出来制作词云图,我们发现广大观众对《八佰》这部战争题材电影表现出强烈的情感。除了好看、不错这些赞美之词以外,更多的是震撼、感人、历史、勿忘国耻等代表着强烈民族色彩的词。
评论类型分布
data['评论类型'] = pd.cut(data['评分'],[0,3,4,6],labels=['差评','中评','好评'],right=False)
df1 = data.groupby('评论类型')['评论内容'].count()
df1 = df1.sort_values(ascending=False)
regions = df1.index.to_list()
values = df1.to_list()
c = (
Pie(init_opts=opts.InitOpts(theme=ThemeType.CHALK))
.add("", zip(regions,values),radius=["40%", "70%"])
.set_global_opts(title_opts=opts.TitleOpts(title="评论类型占比",subtitle="数据来源:猫眼电影",pos_top="0.5%",pos_left = 'center'))
.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}:{d}%",font_size=18))
c.render_notebook()
超过90%的好评率,20亿+的票房不是没有道理。
差评虽不多,但集中在对《八佰》结局的轰炸。
评论数据量TOP10城市
df2 = data.groupby('城市')['评分'].count() #按菜系分组,对评分求平均
df2 = df2.sort_values(ascending=False)[:10]
# print(df2)
bar = Bar(init_opts=opts.InitOpts(theme=ThemeType.CHALK))
bar.add_xaxis(df2.index.to_list())
bar.add_yaxis("",df2.to_list()) #X轴与y轴调换顺序
bar.set_global_opts(title_opts=opts.TitleOpts(title="城市影评数量TOP10",subtitle="数据来源:猫眼电影",pos_top="2%",pos_left = 'center'),
xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(font_size=16)), #更改横坐标字体大小
yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(font_size=16)), #更改纵坐标字体大小
bar.set_series_opts(label_opts=opts.LabelOpts(font_size=16,position='top'))
bar.render_notebook()
成都人对《八佰》评论热情高涨,超过北上广深等大城市。
相关演员提及
result = []
for i in data['评论内容']:
result.append(re.split('[::,,.。!!~·`\;;……、]',i))
def actor_comment(data,result):
actors = pd.DataFrame(np.zeros(5 * len(data)).reshape(len(data),5),
columns = ['欧豪/端午','王千源/羊拐','姜武/老铁','张译/老算盘','张俊一/小湖北'])
for i in range(len(result)):
words = result[i]
for word in words:
if '端午' in word or '欧豪' in word:
actors.iloc[i]['欧豪/端午'] = 1
if '羊拐' in word or '王千源' in word:
actors.iloc[i]['王千源/羊拐'] = 1
if '老铁' in word or '姜武' in word:
actors.iloc[i]['姜武/老铁'] = 1
if '老算盘' in word or '张译' in word:
actors.iloc[i]['张译/老算盘'] = 1
if '小湖北' in word or '张俊一' in word:
actors.iloc[i]['张俊一/小湖北'] = 1
final_result = pd.concat([data,actors],axis = 1)
return final_result
df3 = actor_comment(data,result)
df3.sample(5)
df4 = df3.iloc[:,7:].sum().reset_index().sort_values(0,ascending = False)
df4.columns = ['角色','次数']
df4['占比'] = df4['次数'] / df4['次数'].sum()
c = (
Bar(init_opts=opts.InitOpts(theme=ThemeType.CHALK))
.add_xaxis(df4['角色'].to_list())
.add_yaxis("",df4['次数'].to_list())
.set_global_opts(title_opts=opts.TitleOpts(title="主演及其饰演的角色被提及次数",subtitle="数据来源:猫眼电影",pos_top="2%",pos_left = 'center'),
xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(font_size=16)), #更改横坐标字体大小
yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(font_size=16)), #更改纵坐标字体大小
.set_series_opts(label_opts=opts.LabelOpts(font_size=16,position='top'))
c.render_notebook()
观众评论中提及欧豪和端午的次数最多,不知是因为演技还是颜值?
关于端午的评论
ouhao = df3.loc[df3['欧豪/端午'] == 1,]
text = get_cut_words(content_series=ouhao['评论内容'])
stylecloud.gen_stylecloud(text=' '.join(text), max_words=500,
collocations=False,
font_path='字酷堂清楷体.ttf',
icon_name='fas fa-camera',
#palette='matplotlib.Inferno_9',
size=653,
output_name='./ouhao.png')
Image(filename='./ouhao.png')
关于老算盘的评论
zhangyi = df3.loc[df3['张译/老算盘'] == 1,]
text = get_cut_words(content_series=zhangyi['评论内容'])
stylecloud.gen_stylecloud(text=' '.join(text), max_words=500,
collocations=False,
font_path='字酷堂清楷体.ttf',
icon_name='fas fa-video',
#palette='matplotlib.Inferno_9',
size=653,
output_name='./zhangyi.png')
Image(filename='./zhangyi.png')
关于羊拐的评论
wangqianyuan = df3.loc[df3['王千源/羊拐'] == 1,]
text = get_cut_words(content_series=wangqianyuan['评论内容'])
stylecloud.gen_stylecloud(text=' '.join(text), max_words=500,
collocations=False,
font_path='字酷堂清楷体.ttf',
icon_name='fas fa-thumbs-up',
#palette='matplotlib.Inferno_9',
size=653,
output_name='./wangqianyuan.png')
Image(filename='./wangqianyuan.png')
Python网络爬虫与文本数据分析
rpy2库 | 在jupyter中调用R语言代码
tidytext | 耳目一新的R-style文本分析库
reticulate包 | 在Rmarkdown中调用Python代码
plydata库 | 数据操作管道操作符>>
plotnine: Python版的ggplot2作图库
七夕礼物 | 全网最火的钉子绕线图制作教程
读完本文你就了解什么是文本分析
文本分析在经管领域中的应用概述
综述:文本分析在市场营销研究中的应用
plotnine: Python版的ggplot2作图库
小案例: Pandas的apply方法
stylecloud:简洁易用的词云库
用Python绘制近20年地方财政收入变迁史视频
Wow~70G上市公司定期报告数据集
漂亮~pandas可以无缝衔接Bokeh
YelpDaset: 酒店管理类数据集10+G
“分享”和“在看”是更好的支持!
数据分析与可视化是当今数据分析的发展方向。大数据时代,数据资源具有海量特征。数据分析和可视化主要通过Python数据分析来实现。基于Python的数据分析可视化和技术实现是目前Python数据分析的主要目的,Python可以为数据分析可视化提供思路,在体现数据价值方面发挥着重要作用。因此,在研究数据分析、可视化的过程中,我们可以看到Python具有重要的应用价值。
BeautifulSoup 基于Python 的设计让您可以快速高效地抓取网站数据,Pandas 工具提供简单灵活的数据清理和分析,P
最后一个Dense我们就采用了sigmoid,因为我们的数据集中0是差评,1是好评,我们期望模型的输出结果数值也在0到1之间,这样我们就可以判断是更接近好评还是差评了。这里的分词器和上面我们说的中文分词不同,因为编程语言是老外发明的,人家不用特意分词,他起名叫分词器,就是给词语分类。对于一个词,也是可以嵌入很多维度的。看完了吧,流水线的作用就是进来固定格式的原料,经过一层一层的处理,最终出去固定格式的成品。虽然给它提供了数字,但这不是标准的,有长有短,计算机就是流水线,只吃统一标准的数据。
一、数据抓取利用python软件,抓取豆瓣网上关于《向往的生活》的影视短评,进行网页爬虫,爬虫代码如下:import requestsimport recookies=[cookie1,cookie2,cookie3]url1='https://movie.douban.com/subject/26873657/comments?start=' #《向往的生活 第1季》豆瓣短评网址url2='h...
来源:志斌的Python笔记大家好,我是阳哥~要说十一档最热门的电影,那肯定是长津湖了,在十一档电影中评分排名第一。并且刚刚上映两天,票房就已经突破了六亿,破了十一项记录!本文通过爬取《长...
读者朋友们大家好啊,我是小张~
国庆小长假昨天就已将结束了,我们呢,也各自回到自己的工作岗位,继续开启我们的努力搬砖( 摸鱼)生活
从19年开始,每逢十一就会上映一部以 我和我的* 主题的电影来喜迎国庆,并且按照前两年票房趋势,这部电影的欢迎程度远大于同时期上映的其它电影,票房稳居第一
今年也不例外上映了一部《我和我的父辈》,以4个 片段来讲述父母与孩子之间的故事,内容也受到大众的肯定;
但令人意外的是它的票房,要远低于另一部国庆档《长津湖》,热度和好评数原高于前者,关于其中的具体细节,本文以此来做个影评分