Jul 20, 2013

Fooling around with Python on a Friday night

Browsing and listening to my LP collection... and updating the corresponding Excel file because, well, I have quite a lot of stuff and I can't remember it all when I'm hitting the record stores :D

And then I asked myself, why not write a short program to parse and search this file? A totally pointless little hack, the way I like them. It's too warm to sleep anyway... and "can you still do it, old man?" says the devil on my shoulder.

CSV file, one line per record: sounds like a Python job, baby.

A little while - and quite a bit of profanity - later...

import codecs

def loadRecords(filename, delimiter):
        "Load record collection into a dictionary of dictionaries"
        records = {}
        # The most painful line in this program. F..k you Excel!
        reader = codecs.open(filename, 'r', encoding='ISO-8859-1')
        for line in reader:
                # Some dates are missing or are not integers. Oops :)
                        year = int(row[5])
                        # 1970 is the year Black Sabbath released their 1st album
                        # How's that for a default date, huh?
                        year = 1970      
                records[key] = {'band':row[0], 'album':row[1], 'year':year}
        return records

def findRecords(collection, band, startYear=1900, endYear=2013):
        "Find records by band and year range"
        for key in collection:
                current = collection[key]
                if (current['band'] == band) & ((current['year']) in range(startYear,endYear)):
                        print (band, current['album'], current['year'])
myCollection = loadRecords("records.csv",";")
findRecords(myCollection, "ANATHEMA")
findRecords(myCollection, "AMON AMARTH", 2002)
findRecords(myCollection, "OPETH", 2004, 2008)

You want to see the output, huh? All right:
ANATHEMA The crestfallen E.P. 1992
ANATHEMA They die 1992
ANATHEMA We are the bible 1994
AMON AMARTH Fate of norns 2004
AMON AMARTH Twilight of the thunder god 2008
AMON AMARTH Versus the world 2002
OPETH Ghost reveries 2005
OPETH Orchid 2004

Python is definitely a cool language. I'm sure this code could be perfected and I've also got more feature ideas now... but that's it for today. And yeah, I can still do it ;)

No comments:

Post a Comment