对于我的项目,我使用 mutagen 库从 5000+ mp3 文件中读取 ID3 标签。阅读它们后,我使用它们构造了以下对象。
class Track:
def __init__(self, artist, title, album=None):
self.artist = artist
self.title = title
self.album = None
def __str__(self):
return "Track: %s : %s" % (self.artist,self.title, )
def set_album(self,album):
self.album = album
class Album:
def __init__(self, artist, title, year='', genre='', tracks=None):
self.artist = artist
self.year = year
self.genre = genre
self.title = title
self.tracks = []
def __str__(self):
return "Album: %s : %s [%d]" % (self.artist,self.title,len(self.tracks))
def add_track(self,track):
self.tracks.append(track)
问题是某些文件缺少一些必需的标签(缺少标题、缺少艺术家或两者兼有),导致 KeyValueError
#'TALB' (album title), 'TIT2' (track title), 'TPE1' (artist), 'TDRC' (year), and 'TCON' (genre)
for root, dirs, files in os.walk(dir):
for filename in files:
if filename.lower().endswith(e):
fullname = os.path.join(root, filename)
try:
audio = mutagen.File(fullname)
track = Track(audio['TPE1'],audio['TIT2'])
album = Album(audio['TPE1'], audio['TALB'], audio['TDRC'], audio['TCON'])
excpet Exception as e:
print "Error on %s. %s " % (filename,type(e).__name__)
这会加载具有所有标签的所有文件,这还不够好。我通过使用 ifs 解决了这个问题,它工作正常并且足够快。但是我想知道是否有更好的方法来处理这个问题。