新闻详情

新闻详情

首页 / 资讯中心 / 详情

使用Python分析Spotify听歌数据:从API获取到可视化

发布时间:2026/9/12 9:20:40来源:尧图网络
使用Python分析Spotify听歌数据:从API获取到可视化
1. 项目概述Spotify作为全球最大的音乐流媒体平台之一每天产生海量的用户听歌数据。这些数据不仅记录了我们的音乐偏好还隐藏着许多有趣的个人习惯和趋势。通过Python分析这些数据我们可以可视化自己的音乐品味演变发现潜在的听歌模式创建个性化推荐系统追踪音乐偏好的季节性变化2. 技术准备2.1 获取API访问权限要访问Spotify数据首先需要在 Spotify开发者平台 创建应用登录Spotify开发者账号进入Dashboard点击Create App填写应用名称和描述记下生成的Client ID和Client Secret重要提示请妥善保管Client Secret不要将其公开在代码仓库中2.2 安装必要库我们将使用Spotipy这个官方推荐的Python库pip install spotipy pandas matplotlib seabornSpotipy库封装了Spotify Web API的所有功能让数据获取变得非常简单。3. 数据获取实战3.1 认证流程实现首先建立认证连接import spotipy from spotipy.oauth2 import SpotifyOAuth # 替换为你的应用信息 SPOTIPY_CLIENT_ID your_client_id SPOTIPY_CLIENT_SECRET your_client_secret SPOTIPY_REDIRECT_URI http://localhost:8888/callback # 设置访问范围 scope user-library-read user-top-read user-read-recently-played sp spotipy.Spotify(auth_managerSpotifyOAuth( client_idSPOTIPY_CLIENT_ID, client_secretSPOTIPY_CLIENT_SECRET, redirect_uriSPOTIPY_REDIRECT_URI, scopescope))3.2 获取关键数据获取最近播放的歌曲recently_played sp.current_user_recently_played(limit50) for idx, item in enumerate(recently_played[items]): track item[track] print(f{idx1}. {track[name]} - {, .join([artist[name] for artist in track[artists]])})获取最常听的艺术家top_artists sp.current_user_top_artists(limit10, time_rangemedium_term) print(你的TOP 10艺术家:) for artist in top_artists[items]: print(f- {artist[name]} (人气指数: {artist[popularity]}/100))4. 数据分析与可视化4.1 数据结构化处理将获取的数据转换为Pandas DataFrame以便分析import pandas as pd def get_top_tracks_features(time_rangemedium_term, limit50): top_tracks sp.current_user_top_tracks(limitlimit, time_rangetime_range) tracks_data [] for track in top_tracks[items]: features sp.audio_features(track[id])[0] track_data { name: track[name], artist: , .join([a[name] for a in track[artists]]), duration_ms: track[duration_ms], popularity: track[popularity], danceability: features[danceability], energy: features[energy], key: features[key], loudness: features[loudness], mode: features[mode], speechiness: features[speechiness], acousticness: features[acousticness], instrumentalness: features[instrumentalness], liveness: features[liveness], valence: features[valence], tempo: features[tempo] } tracks_data.append(track_data) return pd.DataFrame(tracks_data) tracks_df get_top_tracks_features()4.2 音乐特征分析使用Seaborn绘制音乐特征雷达图import numpy as np import seaborn as sns import matplotlib.pyplot as plt # 计算平均特征值 features [danceability, energy, speechiness, acousticness, instrumentalness, liveness, valence] avg_features tracks_df[features].mean().values # 创建雷达图 angles np.linspace(0, 2*np.pi, len(features), endpointFalse) angles np.concatenate((angles, [angles[0]])) avg_features np.concatenate((avg_features, [avg_features[0]])) fig plt.figure(figsize(8, 8)) ax fig.add_subplot(111, polarTrue) ax.plot(angles, avg_features, o-, linewidth2) ax.fill(angles, avg_features, alpha0.25) ax.set_thetagrids(angles[:-1] * 180/np.pi, features) ax.set_title(你的音乐特征雷达图, size20, y1.1) plt.show()5. 高级分析技巧5.1 听歌时间模式分析# 获取最近50条播放记录并分析时间分布 recently_played sp.current_user_recently_played(limit50) play_times [item[played_at] for item in recently_played[items]] # 转换为小时并统计 hours [pd.to_datetime(time).hour for time in play_times] hour_dist pd.Series(hours).value_counts().sort_index() plt.figure(figsize(10, 6)) hour_dist.plot(kindbar, color#1DB954) plt.title(你的听歌时间分布) plt.xlabel(小时) plt.ylabel(播放次数) plt.xticks(rotation0) plt.show()5.2 创建个性化推荐基于你的听歌历史生成推荐def get_recommendations(seed_tracksNone, limit10): if seed_tracks is None: top_tracks sp.current_user_top_tracks(limit5)[items] seed_tracks [t[id] for t in top_tracks] recommendations sp.recommendations(seed_tracksseed_tracks, limitlimit) return [(track[name], , .join([a[name] for a in track[artists]])) for track in recommendations[tracks]] print(为你推荐的歌曲:) for idx, (name, artist) in enumerate(get_recommendations()): print(f{idx1}. {name} - {artist})6. 项目扩展思路6.1 长期趋势跟踪建议将数据定期保存到数据库建立时间序列数据集import sqlite3 from datetime import datetime def save_snapshot(): conn sqlite3.connect(spotify_data.db) c conn.cursor() # 创建表(如果不存在) c.execute(CREATE TABLE IF NOT EXISTS top_tracks (date TEXT, name TEXT, artist TEXT, popularity INTEGER)) # 获取当前数据 top_tracks sp.current_user_top_tracks(limit20) today datetime.now().strftime(%Y-%m-%d) # 插入数据 for track in top_tracks[items]: c.execute(INSERT INTO top_tracks VALUES (?, ?, ?, ?), (today, track[name], , .join([a[name] for a in track[artists]]), track[popularity])) conn.commit() conn.close()6.2 构建Web可视化面板使用Flask或Dash构建交互式可视化面板from flask import Flask, render_template import pandas as pd app Flask(__name__) app.route(/) def dashboard(): # 获取数据 top_artists sp.current_user_top_artists(limit10) artists_data [(a[name], a[popularity]) for a in top_artists[items]] return render_template(dashboard.html, artists_dataartists_data) if __name__ __main__: app.run(debugTrue)7. 常见问题解决7.1 认证问题排查如果遇到认证问题检查以下几点确保在Spotify开发者仪表板设置了正确的重定向URI检查Client ID和Secret是否正确确认请求的scope包含你需要的权限本地开发时确保重定向URI与代码中设置的一致7.2 数据获取限制Spotify API有以下限制需要注意最近播放记录最多只能获取最近50条每分钟最多60次请求部分端点需要特定权限scope某些数据(如详细收听历史)不可通过API获取7.3 性能优化建议当需要获取大量数据时使用缓存减少API调用批量请求代替单个请求合理安排请求时间间隔考虑使用异步请求提高效率from functools import lru_cache lru_cache(maxsize32) def get_track_details(track_id): return sp.track(track_id)通过这个项目我们不仅能够深入了解自己的音乐品味还能掌握实用的数据分析技能。从基础的数据获取到高级的可视化分析整个过程展示了Python在数据处理方面的强大能力。
网站建设高端定制企业官网
RELATED

相关资讯

更多精彩内容,欢迎继续阅读

较早相关资讯

最新相关资讯

C语言内存管理:原理、问题与优化实践 2026/9/12 9:50:44

C语言内存管理:原理、问题与优化实践

1. 为什么需要理解C语言内存管理在嵌入式开发中遇到过一个真实案例:某智能家居设备在运行72小时后必然死机。经过排查发现是开发者在处理传感器数据时,循环调用malloc()却忘记free(),导致内存泄漏最终耗尽系统资源。这个经历让我深刻意识到&a…

阅读更多 →
Repomix 隐私政策技术解读:CLI 本地处理、网站临时上传与浏览器扩展的最小权限设计 2026/9/12 9:50:44

Repomix 隐私政策技术解读:CLI 本地处理、网站临时上传与浏览器扩展的最小权限设计

Repomix 隐私政策技术解读:CLI 本地处理、网站临时上传与浏览器扩展的最小权限设计 【免费下载链接】repomix 📦 Repomix is a powerful tool that packs your entire repository into a single, AI-friendly file. Perfect for when you need to feed y…

阅读更多 →
学生装机指南:Intel Ultra 7 265K处理器与高性价比配置方案 2026/9/12 9:50:44

学生装机指南:Intel Ultra 7 265K处理器与高性价比配置方案

1. 为什么选择Intel Ultra 7 265K作为学生装机核心Intel Ultra 7 265K这颗处理器可以说是专为学生群体量身定制的全能型选手。我帮不少学弟学妹装过机,发现他们最常遇到的痛点就是:既要跑专业软件,又想打游戏,预算还特别紧张。265…

阅读更多 →
研发型与通用型项目管理系统的差异与选型指南 2026/9/12 9:50:43

研发型与通用型项目管理系统的差异与选型指南

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

阅读更多 →
Beancount双重记账系统:从原理到实战应用 2026/9/12 9:50:43

Beancount双重记账系统:从原理到实战应用

1. Beancount:双重记账系统的核心价值第一次接触Beancount时,我被它简洁的文本记账方式所震撼。与传统的GUI记账软件不同,这个基于Python的命令行工具通过纯文本文件记录每笔交易,却能自动生成完整的财务报表。它的设计哲学让我想…

阅读更多 →
5 步跑通个人知识库助手:LLM Universe 大模型应用开发完整教程 2026/9/12 9:47:43

5 步跑通个人知识库助手:LLM Universe 大模型应用开发完整教程

5 步跑通个人知识库助手:LLM Universe 大模型应用开发完整教程 【免费下载链接】llm-universe 本项目是一个面向小白开发者的大模型应用开发教程,在线阅读地址:https://datawhalechina.github.io/llm-universe/ 项目地址: https://gitcode.…

阅读更多 →

今日资讯

本周资讯

本月资讯

看完文章仍有疑问?

联系尧图顾问,获取一对一建站咨询

立即免费咨询 📞 400-888-8888
📞