本文将介绍如何使用Python开发一个豆瓣电影分析系统。通过该系统,我们可以获取豆瓣电影的相关数据,并进行一系列分析和可视化展示。
一、数据获取
首先需要从豆瓣电影网站获取电影数据。可以使用第三方库,如BeautifulSoup和requests,来实现网页的爬取和数据的提取。
import requests
from bs4 import BeautifulSoup
def get_movie_data(movie_id):
# 网页链接
url = 'https://movie.douban.com/subject/' + str(movie_id)
# 发送请求
r = requests.get(url)
# 解析网页内容
soup = BeautifulSoup(r.text, 'html.parser')
# 获取电影的相关信息
title = soup.find('span', property="v:itemreviewed").string
rating = soup.find('strong', class_="ll rating_num").string
return {'title': title, 'rating': rating}
上述代码定义了一个get_movie_data函数,用于获取指定电影ID的电影标题和评分。每个电影的信息以字典形式返回。
二、数据分析
获得电影数据之后,我们可以进行各种各样的数据分析。
1. 电影评分分布
我们可以通过统计不同评分的电影数量,绘制出电影评分分布的直方图。
import matplotlib.pyplot as plt
def plot_rating_distribution(movie_data_list):
ratings = [float(movie['rating']) for movie in movie_data_list]
plt.hist(ratings, bins=10, edgecolor='black')
plt.xlabel('Rating')
plt.ylabel('Number of Movies')
plt.title('Movie Rating Distribution')
plt.show()
上述代码定义了一个plot_rating_distribution函数,该函数接收一个包含电影数据的列表作为参数,并将电影评分分布的直方图绘制出来。
2. 电影类型分析
我们还可以通过对电影类型进行统计和分析,来揭示用户对不同类型电影的偏好。
def count_genre(movie_data_list):
genre_count = {}
for movie in movie_data_list:
genres = movie['genres']
for genre in genres:
if genre in genre_count:
genre_count[genre] += 1
else:
genre_count[genre] = 1
return genre_count
上述代码定义了一个count_genre函数,用于统计电影类型的数量。该函数接收一个包含电影数据的列表作为参数,并返回一个字典,键为电影类型,值为对应类型电影的数量。
三、数据可视化
在数据分析的基础上,我们可以使用数据可视化的方式,更直观地展示分析结果。
1. 电影评分分布图
我们可以使用matplotlib库绘制电影评分分布的直方图。
def plot_rating_distribution(movie_data_list):
# 绘制直方图
ratings = [float(movie['rating']) for movie in movie_data_list]
plt.hist(ratings, bins=10, edgecolor='black')
plt.xlabel('Rating')
plt.ylabel('Number of Movies')
plt.title('Movie Rating Distribution')
plt.show()
2. 电影类型统计图
我们可以使用matplotlib库绘制电影类型的统计图,以展示用户对不同类型电影的偏好。
def plot_genre_count(genre_count):
# 将字典按值排序
sorted_genre_count = sorted(genre_count.items(), key=lambda x: x[1], reverse=True)
genres = [genre for genre, count in sorted_genre_count]
counts = [count for genre, count in sorted_genre_count]
# 绘制柱状图
plt.bar(genres, counts)
plt.xlabel('Genre')
plt.ylabel('Number of Movies')
plt.title('Movie Genre Count')
plt.xticks(rotation=45)
plt.show()
上述代码定义了一个plot_genre_count函数,用于绘制电影类型统计的柱状图。该函数接收一个包含电影类型统计信息的字典作为参数。
以上就是使用Python开发的豆瓣电影分析系统的详细介绍。通过对豆瓣电影数据的获取、分析和可视化,我们可以更深入地了解电影的评分分布和类型偏好。