Re: [Rhythmbox-devel] A new pythonic rhythmdb module
- From: Neskie Manuel <neskiem gmail com>
- To: rhythmbox-devel gnome org
- Subject: Re: [Rhythmbox-devel] A new pythonic rhythmdb module
- Date: Sun, 11 Jul 2010 02:17:18 -0700
Here's the module.
import os
import re
class Song():
"""A representation of a song in rhythmbox database."""
def __init__(self, l=[]):
self.fields = l
def __getitem__(self, tag):
for field in self.fields:
if "<%s>" % tag in field:
return field[len(tag)+2:-len(tag)-3]
return None
def __len__(self):
return int(self['duration'])
def __str__(self):
return str(self.fields)
def __trunc__(self):
return int(self['duration'])
def keys(self):
tags = []
for f in self.fields:
tags.append(re.sub('<|>.*$', '', f))
return tags
def values(self):
pass
class RhythmDB():
def __init__(self,songlist=[]):
'''
Open the rhythtmbox database split it into lines find all the song
indices and put them in a list then close it
'''
dbfilename = "%s/.local/share/rhythmbox/rhythmdb.xml" % os.environ.get('HOME')
f = open(dbfilename)
self.rhythmxml = [ line.strip() for line in f.read().split('\n') ]
f.close()
# I'm testing on a Database with 2505 songs, let's see how big can it get.
# My library is 30,000 songs so let's mutliply by 20
# for i in range(20):
# f = open(dbfilename)
# self.rhythmxml = self.rhythmxml + [ line.strip() for line in f.read().split('\n') ]
# f.close()
self.song = songlist
for i, line in enumerate(self.rhythmxml):
if '<entry type="song">' in line:
self.song.append(i)
def __getitem__(self,item):
"""Returns a an item or a slice of a database."""
if isinstance(item,slice):
indices = item.indices(len(self))
return [ self[i] for i in range(*indices) ]
else:
return Song((self.rhythmxml[self.song[n]:self.song[n+1]])[1:-1])
def __len__(self):
"""Returns the number of songs in the database"""
return len(self.song)
def __iter__(self):
for n in range(len(self.song)-1):
yield Song(self.rhythmxml[self.song[n]:self.song[n+1]])
def find(self, tag, value):
"""Generator that find songs with a certain property and value."""
for n in range(len(self.song)-1):
if "<%s>%s</%s>" % (tag, value, tag) in "\n".join(self.rhythmxml[self.song[n]:self.song[n+1]]).lower():
yield Song(self.rhythmxml[self.song[n]:self.song[n+1]])
def get(self, tag, value):
"""Get a list instead of a generator """
return list(self.find(tag, value))
def max(self):
return self[len(self)-2]
def min(self):
return self[0]
def __str__(self):
return "hello"
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]