본문 바로가기

복습용 기술공부

230410 _ spotify api 사용과 tictok에서 빌보드 올라간 곡 체크

@@ 코드 정리해보면서 다시 복습하기

import os
import re
import pickle
from pprint import pprint

파일 로드

# 빌보드 파일 가져오기
with open('billboard_JSON_0410_1_100.pickle', 'rb') as f:
    billboard100w2 = pickle.load(f)

스포티파이 설치 - 조원 위해서

# 스포티파이 설치
!pip install spotipy

스포티파이 api 가져오기

# 스포티파이 api 가져오기
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
client_credentials_manager = SpotifyClientCredentials(client_id='클라이언트아이디', client_secret='클라이언트비밀번호')
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

틱톡에서 유행하는 노래 중 빌보드에 올라간 곡을 찾기 위해서, 스포티파이에 다른 사람들이 올린 '틱톡 유행 곡들' 등의 playlist를 가져왔음.

# playlist_id 적기  _ 주소 마지막 parem 복사해서 넣어주면 됨
playlists = [
    '65LdqYCLcsV0lJoxpeQ6fW',
    '1H3AmBXPtLgPOwwf1WvUYb',
    '49EwFPQUenAFtSeM6CSOGL',
    '7obTIFEedRWoyRj1JLS51X',
    '3oVTiM4z2DYUFhHPR8aqtL',
    '5iYeSAR4fs2XXnSzjowQ9l',
]

틱톡 플레이 리스트 만들기

한 곡에 100회씩만 가져올 수 있음, offset -> n 을 이용해서 101번째 곡부터 다시 가져올 수 있음

# 틱톡 플레이 리스트 만들기
def newtictokList(playlist_id, n = 0, limit = 100):
    name_list = []
    name_dict = {}
    # playlist = sp.playlist(f'spotify:playlist:{playlist_id}')
    playlist2 = sp.playlist_tracks(f'spotify:playlist:{playlist_id}', limit=limit, offset=n*limit)
    for i in range(len(playlist2['items'])):
        # s_title = playlist['tracks']['items'][i]['track']['name']
        s_title = playlist2['items'][i]['track']['name']
        # s_artist = playlist['tracks']['items'][i]['track']['artists'][0]['name']
        s_artist = playlist2['items'][i]['track']['artists'][0]['name']
        name_dict = {
            'title' : s_title,
            'artist' : s_artist
        }
        name_list.append(name_dict)
    return name_list

실행코드 

곡 구분을 위해서 @@를 중간에 삽입, 처음에 받을 때 공백형태 json으로 받아서 이렇게 해

new_tictoks = []
# playlists 넣기, limit은 놔두고 n 값은 변경해서 찾아도 됨
for j in playlists:
    print(j)
    for n in range(5):
        new_tictok = newtictokList(j, n = n)
        # print(new_tictok)
        new_tictok_list = [i['title'] + ' @@ ' + i['artist'] for i in new_tictok]
        new_tictoks.append(new_tictok_list)
print(new_tictoks)

range(5)로 임의로 정한 상태라 리스트 안에 리스트 형태로 들어가짐, 이를 꺼내서 flatten 해주기 위해 재귀형식으로 코드를 짜봄.

def tictok_flatten(new_tictoks):
    tic = []
    for i in new_tictoks:
        if type(i) == list:
            tic += tictok_flatten(i)
        else :
            tic += [i]
    return tic
new_tictoks = tictok_flatten(new_tictoks)

빌보드 파일 받아서 전처리 해주기

# 빌보드 파일 전처리
bil_list=[]
for billboards in billboard100w2:
    # print(billboard_12[billboards])
    for top100 in billboard100w2[billboards]:
        allname = ''
        title = top100['title']
        artist = top100['artist']
        allname = title + ' @@ ' + artist
        bil_list.append(allname)
        
len(set(bil_list)) # 갯수 확인

빌보드와 틱톡의 이름을 비교, 공백 제거, 소문자로 바꿔서 이름 매칭해줌, 어차피 같은 이름에서 파생된 데이터들이기 때문에 굳이 다른 조건을 고민할 필요가 없었음.

# 빌보드와 틱톡 이름 비교
def string_btw(new_tictok_list, bil_list, btw_list=[]):
    # 빌보드 100 가져오기
    for i in bil_list:
        # 틱톡 이름 변경 파일 가져오기
        for j in new_tictok_list:
            if i.lower().replace(' ','') == j.lower().replace(' ',''):
                btw_list.append(i)
    return btw_list

이름 비교후 btw_list에 넣어서 합치기

# 빌보드 틱톡 이름 비교, btw_list = 뒤에는 이전에 받은 btw_list를 넣어서 합칠 것
bll_list2 = string_btw(new_tictoks, bil_list)
btw_list=[]
for i in bil_list:
    # 틱톡 이름 변경 파일 가져오기
    for j in new_tictok_list:
        if i.lower().replace(' ','') == j.lower().replace(' ',''):
            btw_list.append(i)

중복곡 제외하고 올라간 곡들 확인하기

from pprint import pprint
# 빌보드 중복 제외, 틱톡에서 빌보드 올라간 곡들 확인
new_name_any = []
[new_name_any.append(i) for i in set(bll_list2)]
print(new_name_any)


# 리스트 별로 하나씩 해놨기 때문에 그냥 append로 flatten 다시 해주기..
new_name_any2 = []
for i in new_name_any:
    new_name_any2.append(i)
new_name_any2

여기서 저장하고 끝냈는데,

# 곡목록 저장
with open('tiktok_spotify_0410_2.pickle', 'wb') as f:
    pickle.dump(new_name_any, f, pickle.HIGHEST_PROTOCOL)

 

 

------

with open('tiktok_spotify_0410_2.pickle', 'rb') as f:
    pkl = pickle.load(f)

 

튜플로 바꿔서 받아달라고 주문 들어와서 @@ 를 튜플로 바꿔서 다시 보내줌

# 튜플로 받아달라고 주문이 들어와서 @@를 튜플로 바꿔줌
pkl2 = []
for i in pkl:
    # print(i, tuple(i.split(' @@ ')), type(i))
    pkl2.append(tuple(i.split(' @@ ')))
    
pkl2