Python分析《黄蜂女现身》豆瓣影评分析

最近在学习python爬虫以及数据分析,故想做一个简单的项目来检验一下自己最近的学习状况。在豆瓣上查看正在热映的电影有很多,选择了《黄蜂女现身》这部电影来练手,将豆瓣上对它的影评做一个简单的分析吧!后期还会继续对其他的电影进行分析,下次的分析可能会包括地区等属性,此次只是针对评论进行简单的分析。

1、抓取网页数据

首先是抓取网页数据,打开豆瓣电影,点击最近的热映电影后,点击全部评论,我们则选取改网址作为我们的数据来源地址。

import urllib.request
import re

def movie_comment_Crawler(url):

    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/" "537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"}  # 设置模拟请求头

    req = urllib.request.Request(url, headers=headers)

    response = urllib.request.urlopen(req)

    html_data = response.read().decode("utf-8")

    # 因为评论在span中,所以我就直接使用正则表达式来进行匹配
    pattern = r'<span class="short">(.*?)</span>'

    re_comment = re.compile(pattern, re.S)

    comment_list = re_comment.findall(html_data)

    comments = ''
    # 将comment_list列表转换为字符串字符
    for k in range(len(comment_list)):

        comments = comments + (str(comment_list[k])).strip()

    # 将评论保存到txt文件中
    path = "../豆瓣最新电影评论分析/antman_comments.txt"

    with open(path, "a", encoding="utf-8") as f:

        f.write(comments)

# 设置评论的页数
for i in range(0, 10):

    url = "https://movie.douban.com/subject/26636712/comments?start="+str(i * 20)+"&limit=20&sort=new_score&status=P"

    movie_comment_Crawler(url)

2、数据清洗与分析

import re
import jieba   # 分词包
import pandas as pd
from wordcloud import WordCloud  # 词云包
import matplotlib.pyplot as plt
import numpy as np
from scipy.misc import imread


# 读取comments文件
path = "../豆瓣最新电影评论分析/antman_comments.txt"

with open(path, 'r', encoding='utf-8') as file:

    comments = file.readlines()

    comment = ''.join(comments)

# 使用re正则表达式去除多余的标点符号
pattern = re.compile(r'[\u4e00-\u9fa5]+')

filter_data = pattern.findall(comment)

clean_comment = ''.join(filter_data)

# 结巴分词
segment =jieba.lcut(clean_comment, cut_all=True)

words_df = pd.DataFrame({"segment": segment})

# 去除停用词
stopwords = pd.read_excel('stopwords.xlsx', index_col=False, quoting=3, sep="\t",names=["stopword"], encoding="utf-8")

words_df = words_df[~words_df.segment.isin(stopwords.stopword)]

# 词频统计 统计使用 groupby 函数,排序使用 sort 函数。
words_count = words_df.groupby(by=["segment"])["segment"].agg({"count": np.size})

words_count = words_count.reset_index().sort_values(by=["count"], ascending=False)


# 词云显示
bg_mask = imread("background.jpg")  # 读入自己想显示图片的背景

wordcloud = WordCloud(font_path="simhei.ttf", background_color="white",max_font_size=100, max_words=200, width=400,mask=bg_mask)  # 指定字体类型、字体大小和字体颜色

# word_frequence 为字典类型,可以直接传入wordcloud.fit_words()
word_frequence = ({x[0]: x[1] for x in words_count.head(500).values})

wordcloud = wordcloud.fit_words(word_frequence)

# 存储显示
plt.figure(figsize=(9, 6))
plt.imsave('antman.jpg', wordcloud)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()

这里写图片描述

其实图上显示的高频词貌似做的不是很好,毕竟是第一次做的,我还没有真正学习过词云和高频词统计,结巴分词等,都是在网上看别人怎么做的,很多内容都做的不好,望大家批评指正!

猜你喜欢

转载自blog.csdn.net/xiao_pingping/article/details/82111262