一小段代码,通过pylast软件从Last.fm API中吸引top_tracks

时间:2011-12-14 08:50:04

标签: python last.fm

我修改了smbrown.wordpress.com上发布的代码,该代码可以使用Last.fm API提取顶部曲目,如下所示:

 #!/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()

当脚本运行到标有“&lt; ----------- Here --------------”的位置时,我收到一条错误消息:“......第46行,

track = m.groups()[0]

AttributeError:'NoneType'对象没有属性'groups'“

我刚刚在这里呆了一天以上,不知道下一步该做什么。谁能给我一些关于这个问题的线索?

1 个答案:

答案 0 :(得分:1)

显然某些曲目名称与正则表达式不匹配,因此match()返回None。捕获异常并检查track

相关问题