# 用Python获取猫眼30万短评,解读《中国机长》全国热度
使用Python获取猫眼30万短评,解读《中国机长》分析全国粉丝分布情况解读全国热度, 并利用Pyechart、Pandas、jieba分词生成热力图、玫瑰图、词云等.
## 1. **环境要求**
Python3.X+PyEcharts+地图文件包
```python
# 安装pyecharts
pip install pyecharts==0.5.5
# 安装地图文件包
pip install echarts-china-provinces-pypkg # 中国省、市、县、区地图
pip install echarts-china-cities-pypkg
pip install echarts-china-counties-pypkg
pip install echarts-china-misc-pypkg
pip install echarts-countries-pypkg # 全球国家地图
pip install echarts-united-kingdom-pypkg
```
## 2. **数据获取**
调用猫眼评论数据接口
> **http://m.maoyan.com/mmdb/comments/movie/1230121.json?_v_=yes&offset=15&startTime=2019-10-15%2023:59:59**
其中**1230121**是电影id, **offset**是偏移值取值范围是0-1000, 每次爬取结果只有15条评论, 所以 offset每次增加15. **startTime=2019-10-15 2023:59:59**表示获取该时间段之前的数据. 当offset递增到1000时就需要把**startTime**更新成第1000条评论中的时间, 如此循环直到**startTime**更新成电影上映时间就结束获取数据.
![获取电影id](https://img-blog.csdnimg.cn/20191030080935861.jpg)
##### 爬取猫眼短评代码实现
评论数据是在最后才写入到csv文件的, 优化的话可以改成多次分批追加数据到文件从而避免数据丢失. 另外还可以用多线程实现来提升爬取速度但是很有可能被加到黑名单.
```python
import json
import random
import time
import datetime
from urllib.parse import quote
import pandas as pd
import requests
def crawling_data(movie_id, release_time):
## 设置headers和cookie
header = {'Host': 'm.maoyan.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
'Accept-Encoding': 'gzip, deflate',
'DNT': '1',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Cache-Control': 'max-age=0'}
now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
realse_time = datetime.datetime.strptime(release_time, '%Y-%m-%d %H:%M:%S')
# 爬取数据,每次理论上可以爬取1k数据,存在大量重复数据,需要多次执行,最后统一去重
comment_data = pd.DataFrame(columns=['date', 'score', 'city', 'comment', 'nick'])
# 发表评论的时间
start_time = now_time
# 从当前时间往前遍历即从最新评论往前获取数据,当start_time和电影上映时间相同时遍历时结束
while start_time > release_time:
print('正在爬取{}之前1000条评论'.format(start_time))
# 每次只能爬取前1000条数据,每页15条,因此67次循环之后,便不再有数据可以爬取了,需要更新start_time
for i in range(67):
print('正在下载第{}页评论'.format(i + 1))
i *= 15
try:
# 一个url例子:
#http://m.maoyan.com/mmdb/comments/movie/1230121.json?_v_=yes&offset=15&startTime=2019-10-15%2023:59:59
url = 'http://m.maoyan.com/mmdb/comments/movie/{}.json?_v_=yes&offset={}&startTime={}'.format(
str(movie_id), str(i), quote(str(start_time)))
print(url)
time.sleep(random.random())
html = requests.get(url=url, headers=header).content
# 0条数据则退出循环
total = json.loads(html.decode('utf-8'))['total']
if total == 0:
break
data = json.loads(html.decode('utf-8'))['cmts']
if data:
for item in data:
comment_data = comment_data.append(
{'date': item['time'], 'city': item['cityName'],
'score': item['score'], 'comment': item['content'],
'nick': item['nick']}, ignore_index=True)
# 每页中最后一条评论的时间
last_start_time = data[-1]['startTime']
except Exception as e:
print(e)
continue
# 获取1000条数据后更新start_time
start_time = last_start_time
comment_data.to_csv('resources/data.csv', index=False, line_terminator='\r\n')
print('爬取数据完毕!')
```
<br>
##### 数据文件结构
<br>![csv文件结构](https://img-blog.csdnimg.cn/20191101075236205.png)
<br>
## 3. 数据解读
##### 全国评论分布状况
![中国机长全国热力图](https://img-blog.csdnimg.cn/20191030233414369.png)从热度图上可以看出大部分评论者位于我国东部, 这基本与我国人口分布和全国经济水平区域分布一致.只差右下角没被点亮了.
<br>
##### 全国主要城市评论数和打分情况TOP20
![主要城市评论数](https://img-blog.csdnimg.cn/20191031081829324.png)<br>
北上广深位于前五继续宣示着中国一线城市的地位, 值得注意的是成都评论人数领先于上海说明成都人民挺支持英雄机长的毕竟川航挡风玻破碎后飞机就在成都备降, 东莞位于第六远远超过后面一大票省会城市( 嘿嘿,东莞要崛起了毕竟华为都开始搬到东莞了 <img src="https://img-blog.csdnimg.cn/20191031201710617.jpg" width = 20 height =20 align="center" /> )
至于各大城市评分嘛,最高平均分4.84分、最低分4.7分,啧啧这分数,不管你信不信我反正是不信. 波动范围.在4.6到4.8之间各大城市表现简直一模一样.
<br><br>
##### 评分星级玫瑰图
<br>
![评分星级](https://img-blog.csdnimg.cn/2019103122414296.png)<br>
绝大评论者都给了五星好评, 少部分给了一星差评. 不知道五星好评能返现不 :joy:
<br><br>
##### 生成词云
![词云](https://img-blog.csdnimg.cn/20191031225009346.jpg)<br>
词云主要词语是震撼、真实、敬畏、感动、好看,表明该片在国庆档上映取得了不错的口碑用来给祖国母亲庆生也是极好的. 在空难片中应该算中等水平. 之前刷B站看到了九筒解说二十年前拍的国产首部空难片[《紧急迫降》](https://www.bilibili.com/video/av71198947)突然让我回忆起童年看过的电影频道 , 该片是根据东航客机起落架放不下通过各种操作最后惊险迫降上海虹桥机场的故事改编,即使在现在看来也是相当不错的影片. 希望国产影片能越做越好吧. :grinning:
<br>
## 4. 代码实现
<br>
##### 数据处理
用pandas 加载数据文件data.csv去重后写入到drop_duplicates_data.csv, 按照城市进行聚合获取每个城市的评论人数和平均评分. 还可以按照用户名nick去重, 另外行结束符line_terminator可以是自定义的一串特定字符这样按行读取的时候就可以避免内容包含回车换行引起的错误. 需要注意的是score列 需要转成float类型
```python
import pandas as pd
import traceback
from pyecharts import Bar, Geo, Line, Overlap, Pie
## 可以直接读取我们已经爬到的数据进行分析,score列转成float类型
try:
comment_data = pd.read_csv('resources/data.csv', encoding="GBK", dtype={'score': float})
except Exception as e:
pass
print(traceback.format_exc())
# 去重
comment_data = comment_data.drop_duplicates()
comment_data.to_csv('resources/drop_duplicates_data.csv', index=False, line_terminator='\r\n')
grouped = comment_data.groupby(['city'])
grouped_pct = grouped['score']
# 按城市分组后进行聚合
city_com = grouped_pct.agg(['mean',
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
使用Python获取猫眼30万短评,解读《中国机长》分析全国粉丝分布情况解读全国热度, 并利用Pyechart、Pandas、jieba分词生成热力图、玫瑰图、词云等. 调用猫眼评论数据接口 http://m.maoyan.com/mmdb/comments/movie/1230121.json?_v_=yes&offset=15&startTime=2019-10-15%2023:59:59
资源推荐
资源详情
资源评论
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
收起资源包目录
![package](https://csdnimg.cn/release/downloadcmsfe/public/img/package.f3fc750b.png)
![folder](https://csdnimg.cn/release/downloadcmsfe/public/img/folder.005fa2e5.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/UNKNOWN.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/UNKNOWN.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/UNKNOWN.png)
![folder](https://csdnimg.cn/release/downloadcmsfe/public/img/folder.005fa2e5.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/UNKNOWN.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/JPG.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/JPG.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/HTML.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/HTML.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/UNKNOWN.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/UNKNOWN.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/HTML.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/UNKNOWN.png)
![file-type](https://csdnimg.cn/release/download/static_files/pc/images/minetype/UNKNOWN.png)
共 13 条
- 1
资源评论
![avatar-default](https://csdnimg.cn/release/downloadcmsfe/public/img/lazyLogo2.1882d7f4.png)
- m0_532966302022-12-20感谢大佬分享的资源给了我灵感,果断支持!感谢分享~
![avatar](https://profile-avatar.csdnimg.cn/d5b8e16cddf148da83293d5bb68d9224_admin_maxin.jpg!1)
博士僧小星
- 粉丝: 1943
- 资源: 5903
上传资源 快速赚钱
我的内容管理 展开
我的资源 快来上传第一个资源
我的收益
登录查看自己的收益我的积分 登录查看自己的积分
我的C币 登录后查看C币余额
我的收藏
我的下载
下载帮助
![voice](https://csdnimg.cn/release/downloadcmsfe/public/img/voice.245cc511.png)
![center-task](https://csdnimg.cn/release/downloadcmsfe/public/img/center-task.c2eda91a.png)
安全验证
文档复制为VIP权益,开通VIP直接复制
![dialog-icon](https://csdnimg.cn/release/downloadcmsfe/public/img/green-success.6a4acb44.png)