公司动态
Python+Spotify API打造个性化音乐分析工具
1. 项目概述用Python解锁你的Spotify音乐DNA去年冬天整理年度歌单时我发现Spotify的年度回顾功能虽然精美但数据维度实在太有限。作为常年日均听歌4小时的重度用户我决定用Python把自己的播放记录扒个底朝天。这个项目不需要复杂的爬虫技术Spotify官方API对个人开发者非常友好只需要30行核心代码就能提取包括歌曲特征、收听时段、艺人国籍等20维度的数据。2. 环境准备与API配置2.1 开发环境搭建推荐使用Python 3.8版本主要依赖库包括pip install spotipy pandas matplotlib seabornspotipySpotify官方Python SDK1.2MBpandas数据处理核心工具15MBmatplotlib/seaborn可视化黄金组合8MB注意国内安装可能遇到SSL证书问题建议先升级pip并配置清华镜像源2.2 Spotify开发者账号申请登录 Spotify开发者仪表盘创建新应用类型选Personal Use记录下Client ID和Client Secret在设置中添加回调地址http://localhost:8888/callback3. 核心数据抓取实现3.1 认证流程封装import spotipy from spotipy.oauth2 import SpotifyOAuth scope user-library-read user-top-read user-read-recently-played sp spotipy.Spotify(auth_managerSpotifyOAuth( client_idYOUR_CLIENT_ID, client_secretYOUR_CLIENT_SECRET, redirect_urihttp://localhost:8888/callback, scopescope))3.2 关键数据端点解析端点数据量示例用途/me/top/{type}50条分析长期偏好/me/player/recently-played50条短期行为分析audio-features/{id}单曲音乐特征工程3.3 完整数据采集示例def get_audio_features(track_ids): features [] for i in range(0, len(track_ids), 50): batch track_ids[i:i 50] features sp.audio_features(batch) return pd.DataFrame(features) top_tracks sp.current_user_top_tracks(limit50, time_rangelong_term) track_ids [item[id] for item in top_tracks[items]] audio_df get_audio_features(track_ids)4. 数据分析与可视化实战4.1 音乐特征雷达图import matplotlib.pyplot as plt features [danceability, energy, speechiness, acousticness, instrumentalness, liveness] plt.figure(figsize(10,6)) for i in range(3): values audio_df.iloc[i][features].tolist() values values[:1] # 闭合雷达图 angles [n / float(len(features)) * 2 * pi for n in range(len(features))] angles angles[:1] plt.polar(angles, values, linewidth1, linestylesolid, labelaudio_df.iloc[i][name])4.2 收听时间模式分析recent_plays sp.current_user_recently_played(limit50) play_hours [datetime.strptime(item[played_at], %Y-%m-%dT%H:%M:%S.%fZ).hour for item in recent_plays[items]] plt.hist(play_hours, bins24, edgecolorblack) plt.xticks(range(24)) plt.title(Daily Listening Pattern)5. 高级技巧与避坑指南5.1 速率限制应对策略默认限制30请求/秒建议添加延时time.sleep(0.5)between batches错误处理模板try: response sp.current_user_saved_tracks() except spotipy.exceptions.SpotifyException as e: if e.http_status 429: retry_after int(e.headers[Retry-After]) time.sleep(retry_after)5.2 数据持久化方案推荐使用SQLite存储历史数据import sqlite3 conn sqlite3.connect(spotify_data.db) audio_df.to_sql(audio_features, conn, if_existsappend, indexFalse)6. 创意分析方向拓展6.1 音乐口味变迁分析通过对比不同time_range参数获取的数据short_term4周medium_term6个月long_term数年6.2 艺人关系网络图使用NetworkX库构建import networkx as nx G nx.Graph() for artist in related_artists: G.add_edge(main_artist, artist[name], weightartist[popularity]) nx.draw(G, with_labelsTrue, node_size50)我在持续分析自己3年的收听数据后发现几个反直觉的结论工作日反而比周末听更多电子音乐雨天会显著提高古典乐播放量。这些洞察用现成的年度回顾永远无法获得。建议每月运行一次脚本建立时间序列数据集你会惊讶于自己音乐品味的微妙变化规律。