一、使用网络爬虫技术抓取《穿靴子的猫2》在豆瓣电影上的所有页的影评数据抓取地址:httpsmoviedoubancomsubject25868125
抓取影评数据的具体步骤如下:
-
使用 Python 编程语言,安装需要的库,如 requests、BeautifulSoup、pandas、re、time 等。
-
使用 requests 库发起 HTTP 请求,获取豆瓣电影《穿靴子的猫2》的影评页面。
-
使用 BeautifulSoup 库解析 HTML 页面,获取影评数据。
-
分析分页规律,循环遍历所有的页数,获取每一页的影评数据。
-
将获取到的影评数据存储到本地文件或数据库中,备份数据以便后续处理。
-
对数据进行清洗和处理,如去除 HTML 标签、过滤无用信息、统计数据等。
-
使用 pandas 库将数据转换为 DataFrame 格式,方便进行数据分析和可视化。
-
对数据进行分析,如影评数量、评分分布、关键词提取等。
-
使用 matplotlib、pyecharts 等库进行数据可视化,生成图表展示分析结果。
以下是示例代码:
import requests
from bs4 import BeautifulSoup
import pandas as pd
import re
import time
# 设置请求头,模拟浏览器访问
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 定义函数,获取每一页的影评数据
def get_comments(url):
res = requests.get(url, headers=headers)
soup = BeautifulSoup(res.text, 'html.parser')
comments = soup.find_all('div', class_='comment-item')
data = []
for comment in comments:
# 获取用户名称
name = comment.find('span', class_='comment-info').find('a').text.strip()
# 获取用户评分
rating = comment.find('span', class_='comment-info').find_all('span')[1]['class'][0][7:]
# 获取影评时间
time = comment.find('span', class_='comment-info').find_all('span')[3]['title']
# 获取影评内容
content = comment.find('span', class_='short').text.strip()
# 获取有用数
useful = comment.find('span', class_='votes').text
useful = re.findall('\d+', useful)[0]
data.append([name, rating, time, content, useful])
return data
# 主函数,抓取所有影评数据
def main():
# 定义要抓取的页数
pages = 10
# 定义空数据框,用于存储所有影评数据
df = pd.DataFrame(columns=['name', 'rating', 'time', 'content', 'useful'])
for i in range(pages):
# 构造每一页的 URL
url = f'https://movie.douban.com/subject/25868125/comments?start={i*20}&limit=20&sort=new_score&status=P'
# 获取当前页的影评数据
data = get_comments(url)
# 将数据转换为数据框格式,添加到总数据框中
df_temp = pd.DataFrame(data, columns=['name', 'rating', 'time', 'content', 'useful'])
df = pd.concat([df, df_temp], ignore_index=True)
# 随机等待一段时间,避免被封 IP
time.sleep(1 + 2 * float(i))
# 将数据保存到本地文件
df.to_csv('comments.csv', index=False)
if __name__ == '__main__':
main()
二、使用文本挖掘技术,分析《穿靴子的猫2》影评中的关键词、评分分布等信息。
主要步骤如下:
-
读取保存下来的影评数据,使用 pandas 库将数据转换为 DataFrame 格式。
-
对数据进行清洗和处理,如去除 HTML 标签、过滤无用信息等。
-
使用 jieba 分词工具对影评内容进行分词处理,获取每个词的出现次数。
-
利用 wordcloud 库生成词云图,展示影评中的关键词。
-
利用 matplotlib 库生成评分分布图,展示影评者对电影的评价。
以下是示例代码:
import pandas as pd
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 定义函数,分词并统计词频
def word_count(text):
# 使用 jieba 分词工具进行分词
words = jieba.cut(text)
# 统计每个词的出现次数
word_count = {}
for word in words:
if len(word) > 1:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
return word_count
# 主函数,分析影评数据
def main():
# 读取影评数据
df = pd.read_csv('comments.csv')
# 清洗数据,去除无用信息
df.dropna(inplace=True)
df['content'] = df['content'].str.strip()
# 使用 jieba 分词工具进行分词,并统计词频
word_counts = df['content'].apply(word_count)
# 合并词频数据
word_count = {}
for wc in word_counts:
for word, count in wc.items():
if word in word_count:
word_count[word] += count
else:
word_count[word] = count
# 生成词云图
wc = WordCloud(font_path='msyh.ttc', background_color='white', width=800, height=600, max_words=100, max_font_size=80)
wc.generate_from_frequencies(word_count)
wc.to_file('wordcloud.png')
# 生成评分分布图
ratings = df['rating'].value_counts().sort_index()
plt.bar(ratings.index, ratings.values)
plt.xlabel('Rating')
plt.ylabel('Count')
plt.title('Rating Distribution')
plt.savefig('rating.png')
plt.show()
if __name__ == '__main__':
main()
分析结果:
-
影评中的关键词词云图展示了观众对电影的评价。其中出现频率较高的词包括“猫”,“喜剧”,“有趣”,“动画”,“情节”,“音乐”等。
-
评分分布图展示了观众对电影的评价分布。其中,高分(8-10分)影评数量最多,低分(1-3分)影评数量较少,整体呈现正偏态分布
原文地址: http://www.cveoy.top/t/topic/g7mX 著作权归作者所有。请勿转载和采集!