基于内容推的例子代码有解析,有输出结果
时间: 2023-05-28 15:02:11 浏览: 147
数据推送示例
以下是一个简单的基于内容推的例子代码,模拟了一个电影推荐系统:
```python
# 定义电影数据
movies = {
'The Shawshank Redemption': ['Drama', 'Crime'],
'The Godfather': ['Drama', 'Crime'],
'The Godfather: Part II': ['Drama', 'Crime'],
'The Dark Knight': ['Action', 'Crime', 'Drama'],
'12 Angry Men': ['Drama'],
'Schindler's List': ['Drama', 'History', 'War'],
'The Lord of the Rings: The Return of the King': ['Action', 'Adventure', 'Drama'],
'Pulp Fiction': ['Crime', 'Drama'],
'Fight Club': ['Drama'],
'Forrest Gump': ['Drama', 'Romance']
}
# 定义用户喜好数据
user_preferences = {
'Action': 5.0,
'Adventure': 4.0,
'Crime': 3.0,
'Drama': 5.0,
'History': 1.0,
'War': 1.0,
'Romance': 2.0
}
# 基于电影数据和用户喜好数据,计算每个电影的预测偏好得分
movie_scores = {}
for movie in movies:
score = 0.0
for genre in movies[movie]:
if genre in user_preferences:
score += user_preferences[genre]
movie_scores[movie] = score
# 按照预测偏好得分从高到低排序,推荐前三个电影
recommended_movies = sorted(movie_scores, key=movie_scores.get, reverse=True)[:3]
# 输出推荐电影列表
print('Recommended movies:')
for movie in recommended_movies:
print(f'{movie} ({", ".join(movies[movie])})')
```
这个例子中,我们首先定义了一些电影数据和一个用户的喜好数据,然后基于这些数据来计算每个电影的预测偏好得分,最后按照得分从高到低排序,推荐前三个电影。运行结果如下:
```
Recommended movies:
The Shawshank Redemption (Drama, Crime)
The Godfather (Drama, Crime)
The Godfather: Part II (Drama, Crime)
```
由于用户的喜好数据是偏向剧情和犯罪类型的,因此推荐结果也是这两种类型的电影。
阅读全文