[超详细] Python3爬取豆瓣影评、去停用词、词云图、评论关键词绘图处理

爬取豆瓣电影《大侦探皮卡丘》的影评,并做词云图和关键词绘图
第一步:找到评论的网页url。
https://movie.douban.com/subject/26835471/comments?start=0&limit=20&sort=new_score&status=P
第二步:鼠标放在评论上右键检查,分析源代码,确定抓取的内容。

<span class="short">萌就行了!这个世界观感觉梦想成真了!</span>
1
如上,只要抓取该标签下的文本就好,这里可以用正则表达式,里面的文本内容用(.*?)抓取。

第三步:观察分页情况。
点击下一页,发现链接变为:
https://movie.douban.com/subject/26835471/comments?start=20&limit=20&sort=new_score&status=P
发现只有start=后面的数字改变,每页20条评论,每页*20即可

导入模块
这些模块可在cmd下输入pip install 模块名,或者pycharm中setting-Project Interpreter里右边的+号安装

import requests
import re
from wordcloud import WordCloud
import jieba
from PIL import Image
import jieba.analys
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
1
2
3
4
5
6
7
8
9
10
1、用requests获取url
因为爬虫次数较多可能IP被封,所以找了个代理IP,参数里习惯性加上headers伪装成浏览器访问。

def getHtml(url):
# 获取url页面
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'}
proxies = {'http': '61.135.217.7:80'}
response = requests.get(url, headers=headers, proxies=proxies)
response.encoding = 'utf-8'
return response.text
1
2
3
4
5
6
7
8
2、用正则解析网页,提取文本,返回评论列表
def getComment(url):
# 用正则提取评论文本,返回一个列表
html = getHtml(url) #调用上一个函数
comments = re.findall('<span class="short">(.*?)</span>', html, re.S) # re.S记得加上,空字符串
onepageComments = [] # 创建一个空列表,存放评论
#用正则表达式解析出来的是一个列表,遍历列表,将每一个评论取出,添加到空列表里,每个评论后面换行
for i in comments:
onepageComments.append(i + '\n')
return onepageComments
1
2
3
4
5
6
7
8
9
3、分页、函数回调,写入本地文件
if __name__ == '__main__':
f = open(r'大侦探皮卡丘部分影评.txt', 'w', encoding='utf-8')
#这里抓取10页内容,如果太多页可能需要登录豆瓣账号,然后在requests.get参数中增加一个cookies参数即可浏览后面的评论
for page in range(10):
url = 'https://movie.douban.com/subject/26835471/comments?start=' + str(
20 * page) + '&limit=20&sort=new_score&status=P' # 分页
# print('第%s页的评论:' % (page+1)) #这里可以知道正在爬取的是第几页的评论,方便自己核对
for i in getComment(url):
f.write(i) # 将每一页评论都写入本地文件中
# print(i) # 打印所有评论
# print('\n') # 每页换行
1
2
3
4
5
6
7
8
9
10
11
4、词云图
先将抓取的文件打开,注意编码

comments = open('大侦探皮卡丘部分影评.txt', 'r', encoding='utf-8').read()
1
以下词云图分几种情况,都可以尝试跑一遍看看效果,最全面的可以直接看第3小点。

4.1 如果不分词
wc = WordCloud(background_color='white', # 设置背景颜色
font_path="C:\Windows\Fonts\msyh.ttf", # 设置中文字体
max_font_size=60, # 设置字体最大值
random_state=30, # 设置有多少种随机生成状态,即有多少种配色方案
width=800,
height=600
).generate(comments) # 生成词云
# 展示词云图
plt.figure(figsize=(20, 10)) #设置画布大小
plt.imshow(wc, interpolation='bilinear')
plt.axis("off") #去掉坐标轴
plt.show()
1
2
3
4
5
6
7
8
9
10
11
12
4.2 jieba分词
wordlist = jieba.cut(str(comments), cut_all=False) #精确模式
wl = " ".join(wordlist)
wc = WordCloud(background_color='white', # 设置背景颜色
font_path="C:\Windows\Fonts\msyh.ttf", # 设置中文字体
max_font_size=60, # 设置字体最大值
random_state=30, # 设置有多少种随机生成状态,即有多少种配色方案
width=800,
height=600
).generate(wl) # 注意这里面的参数是wl
# 展示词云图
plt.figure(figsize=(20, 10)) #设置画布大小
plt.imshow(wc, interpolation='bilinear')
plt.axis("off") #去掉坐标轴
plt.show()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
4.3 结巴分词,加上萌图,去停用词,并保存图片
相关的模块要导进来
这里有一个哈工大停用词表,可自行网上下载
然后下载一张词云用的背景图(我这里是pikaqiu.png,一张皮卡丘的图)

wordlist = jieba.cut(str(comments), cut_all=False) #精确模式
wl = " ".join(wordlist)
# 设置背景图
mask = np.array(Image.open('pikaqiu.png', 'r'))
# 设置停用词
stopwords_file = open('哈工大停用词表.txt', 'r')
stopwords = [words.strip() for words in stopwords_file.readlines()]
# 设置词云(里面多加了几个参数)
wc = WordCloud(background_color='white', # 设置背景颜色
mask=mask, # 设置背景图片
max_words=2000, # 设置最大词数
stopwords=stopwords, # 设置停用词
font_path="C:\Windows\Fonts\msyh.ttf", # 设置中文字体
max_font_size=60, # 设置字体最大值
random_state=30, # 设置有多少种随机生成状态,即有多少种配色方案
width=600,
height=800
).generate(wl) # 生成词云

# 展示词云图
plt.figure(figsize=(8, 6)) #设置画布大小
plt.imshow(wc, interpolation='bilinear')
plt.axis("off") #去掉坐标轴
plt.show()
wc.to_file('result.jpg') #存为图片
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
到这里基本就完成了

5、取前20个评论关键词
# withWeight=True一并返回关键词、权重值
keywords = jieba.analyse.extract_tags(
comments, topK=20, withWeight=True, allowPOS=("n", "v")) # 指定名词和动词

# 变成dataframe格式
comm = pd.DataFrame(keywords)
for item in keywords:
print(item[0], item[1])

# 设置画布大小
plt.figure(figsize=(10, 8))
#显示中文
mpl.rcParams['font.sans-serif'] = ['SimHei']
# 画图
plt.bar(comm[0], comm[1], color="c")
# 设置标签,标题,调整大小
plt.xlabel('词语', fontsize=20)
plt.ylabel('权重', fontsize=20)
plt.title('评论词频', fontsize=20)
plt.tick_params(labelsize=10)
# 在每个直条上加标签
for a, b in zip(comm[0], comm[1]):
plt.text(a, b, '%.2f' % b, ha='center', va='bottom', fontsize=10)
plt.show(http://www.my516.com)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

---------------------

猜你喜欢

转载自www.cnblogs.com/hyhy904/p/11082288.html