[Tutor] tagging pieces of information

Eric Abrahamsen eric at abrahamsen.com
Tue Aug 28 05:31:45 CEST 2007


On Aug 28, 2007, at 11:07 AM, Che M wrote:

> I don't know if there are any preexisting Python structures which  
> would help
> with this or if it has to be done by scratch, or if it is easy or  
> difficult.
>   I also don't know what are good ideas for ways to save the tags,  
> whether
> in a text file, in a database (if so, comma separated in one  
> cell?), or some
> other means, and how to associate them with the data chunk they  
> refer to,
> and lastly how to search for them.

My first thought would be to create a class for your 'data chunks',  
and then make 'tags' a class attribute that is created empty on  
initialization. The basic code would look like:

class Data_chunk(object):
     def __init__(self):
         self.tags = set()

Then every time you create a new data chunk like so:

my_data = Data_chunk()

You can add, remove and search for tags using the set methods (I made  
it a set because that seemed appropriate to a tagging feature, you  
could use a list or something else):

my_data.tags.add('dogs')
my_data.tags.add('cats')
if 'dogs' in my_data.tags:
	print "It's about dogs"
my_data.tags.remove('dogs')
print my_data.tags

The pickle module is usually simplest and most convenient for long- 
term data storage.

Enjoy!

E


More information about the Tutor mailing list