1

我修改了在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()

当脚本运行到标记为“<------------Here--------------”的位置时,我收到一条错误消息:“.. .. 第 46 行,在

轨道 = m.groups()[0]

AttributeError:“NoneType”对象没有属性“组””

我只是在这里停留了一天多,不知道下一步该做什么。谁能给我一些关于这个问题的线索?

4

1 回答 1

1

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

于 2011-12-14T09:17:35.490 回答