2011-12-14 42 views
1

吸引從Last.fm API top_tracks我修改發表了關於smbrown.wordpress.com其可以提取使用Last.fm API如下頂部軌道的代碼:一小片的代碼,其通過pylast軟件

#!/usr/bin/python 

import time 
import pylast 
import re 

from md5 import md5 


user_name = '*******' 
user_password = '*******' 
password_hash = pylast.md5("*******") 
api_key = '***********************************' 
api_secret = '****************************' 
top_tracks_file = open('top_tracks_wordle.txt', 'w') 
network = pylast.LastFMNetwork(api_key = api_key, api_secret = api_secret, username =    user_name, password_hash = password_hash) 



# to make the output more interesting for wordle viz. 
# run against all periods. if you just want one period, 
# delete the others from this list 
time_periods = ['PERIOD_12MONTHS', 'PERIOD_6MONTHS', 'PERIOD_3MONTHS', 'PERIOD_OVERALL'] 
# time_periods = ['PERIOD_OVERALL'] 
##### 
## shouldn't have to edit anything below here 
##### 
md5_user_password = md5(user_password).hexdigest() 

sg = pylast.SessionKeyGenerator(network) #api_key, api_secret 
session_key = sg.get_session_key(user_name, md5_user_password) 

user = pylast.User(user_name, network) #api_key, api_secret, session_key 

top_tracks = [] 
for time_period in time_periods: 
    # by default pylast returns a seq in the format: 
    # "Item: Andrew Bird - Fake Palindromes, Weight: 33" 
    tracks = user.get_top_tracks(period=time_period) 

    # regex that tries to pull out only the track name (
    # for the ex. above "Fake Palindromes" 
    p = re.compile('.*[\s]-[\s](.*), Weight: [\d]+') 

    for track in tracks: 
     m = p.match(str(track)) 
     **track = m.groups()[0]**     <-----------Here--------------- 
     top_tracks.append(track) 
    # be nice to last.fm's servers 
    time.sleep(5) 

top_tracks = "\n".join(top_tracks) 
top_tracks_file.write(top_tracks) 
top_tracks_file.close() 

當腳本運行到標有「< ----------- Here --------------」的位置,我收到一條錯誤消息:「.... (線46,在

軌道= m.groups)[0]

AttributeError的: 'NoneType' 對象沒有屬性 '基團'」

我剛在這裏住了一天,不知道下一步該怎麼做。任何人都可以給我一些關於這個問題的線索嗎?

回答

1

顯然有些軌道名稱與您的正則表達式不匹配,所以match()返回None。抓住例外並檢查track