返回

电影影评分析报告:基于MongoDB和PyMongo的实践指南

后端

  1. 数据爬取

首先,我们需要从豆瓣网爬取电影信息和影评数据。

import requests
from bs4 import BeautifulSoup
import re

# 请求豆瓣TOP10的电影信息页面
response = requests.get('https://movie.douban.com/top250')

# 解析HTML内容
soup = BeautifulSoup(response.text, 'html.parser')

# 提取电影信息
movies = []
for movie in soup.find_all('div', class_='item'):
    title = movie.find('span', class_='title').text
    score = movie.find('span', class_='rating_num').text
    movies.append({'title': title, 'score': score})

# 提取影评信息
reviews = []
for review in soup.find_all('div', class_='review'):
    content = review.find('span', class_='short-content').text
    reviews.append({'content': content})

# 将爬取的信息封装成dict
data = {'movies': movies, 'reviews': reviews}

2. 数据预处理

接下来,我们将对爬取的数据进行预处理。

import pandas as pd
import numpy as np

# 将数据转换为DataFrame
df = pd.DataFrame(data)

# 清洗数据
df['score'] = df['score'].str.replace(' ', '')
df['content'] = df['content'].str.replace('\n', '')

# 去除空值
df.dropna(inplace=True)

# 将电影名称作为索引
df.set_index('title', inplace=True)

3. MongoDB存储

现在,我们将使用PyMongo将预处理后的数据存储到MongoDB数据库中。

import pymongo

# 连接MongoDB数据库
client = pymongo.MongoClient('mongodb://localhost:27017')

# 创建数据库和集合
db = client.movie_reviews
collection = db.reviews

# 将数据插入集合中
collection.insert_many(df.to_dict('records'))

4. PyMongo操作

接下来,我们将使用PyMongo对数据进行查询和分析。

# 查询电影评分大于等于8分的电影
movies = collection.find({'score': {'$gte': 8}})

# 查询每部电影的影评数量
reviews_count = collection.aggregate([
    {'$group': {'_id': '$title', 'count': {'$sum': 1}}},
    {'$sort': {'count': -1}}
])

# 查询含有特定关键词的影评
keywords = ['好看', '烂片']
reviews_with_keywords = collection.find({
    '$text': {'$search': ' '.join(keywords)}
})

5. 情感分析

接下来,我们将使用TextBlob对影评进行情感分析。

from textblob import TextBlob

# 创建情感分析器
sentiment_analyzer = TextBlob

# 对每条影评进行情感分析
for review in collection.find():
    review['sentiment'] = sentiment_analyzer(review['content']).sentiment.polarity

# 计算每部电影的平均情感得分
movie_sentiment = collection.aggregate([
    {'$group': {'_id': '$title', 'avg_sentiment': {'$avg': '$sentiment'}}},
    {'$sort': {'avg_sentiment': -1}}
])

6. 数据可视化

最后,我们将使用Seaborn对数据进行可视化。

import seaborn as sns

# 绘制电影评分分布图
sns.histplot(df['score'], bins=10)

# 绘制每部电影的影评数量柱状图
sns.barplot(x=reviews_count['_id'], y=reviews_count['count'])

# 绘制电影情感得分分布图
sns.histplot(movie_sentiment['avg_sentiment'], bins=10)

# 绘制评论词云
wordcloud = WordCloud().generate(' '.join(df['content']))
plt.imshow(wordcloud)