Monday, July 28, 2008

My First OO in Python

This job is associated my previous blogs, this, this and this. The difference is I am converting portion of it to OO in Python.

The input files are two mapping files namely the sitename mapping to Address and sitename mapping to ID. The main loop will go through every record in the input file and substitute the sitename with the mapping.

#! /usr/bin/python


import sys
if len(sys.argv) != 2:
 print "Usage: %s <file>" % sys.argv[0]
 exit(1)

class Map:
 def __init__(self,mapfile,sep):
  import os
  self.mapfile=mapfile
  self.sep=sep
  self.mapping={}

  for line in open(self.mapfile,'r'):
   line=line.rstrip()
   [k,v]=line.split(self.sep,1)
   self.mapping[k]=v

 def getValue(self,k):
  try:
   v=self.mapping[k]
  except:
   v=''
  return v



key2add=Map('sitename-address-mapping.txt',':')
key2id=Map('sitename-id-mapping.txt',':')

for line in open(sys.argv[1],'r'):
 key=line.rstrip()
 print "%s\t%s\t%s" % (key, key2id.getValue(key), key2add.getValue(key))

It is a lot cleaner in OO than the procedural way in Tcl, but it requires more planning upfront. I am definitely looking for more opportunities to do things in OO

Labels:

0 Comments:

Post a Comment

<< Home