Guest
Public paste!

upload

By: a guest | Jun 19th, 2009 | Syntax: Python | Size: 1.96 KB | Hits: 163 | Expires: Never
Copy text to clipboard
  1. #!/usr/bin/python
  2.  
  3. #This script requires Python Version 2.5 or higher
  4.  
  5. #Define fields that should be selected
  6. resultFields = (7, 8, 9, 12, 14, 15)
  7.  
  8. class ParseSGExport:
  9.     "Creates communication matrix from SG log export (csv file)"
  10.    
  11.     def __init__(self):
  12.         "Define working list"
  13.  
  14.         self.list = []
  15.    
  16.    
  17.     def unique(self):
  18.         "Removes duplicates from list"
  19.  
  20.         uniqueList = []
  21.         for item in self.list:
  22.                 if item not in uniqueList:
  23.                     uniqueList.append(item)
  24.         self.list = uniqueList
  25.  
  26.  
  27.     def sort(self):
  28.         "Sorts list by colum 1, 2 and 4"
  29.  
  30.         from operator import itemgetter
  31.  
  32.         description = self.list.pop(0)
  33.         self.list.sort(key=itemgetter(0, 1, 3))
  34.         self.list.insert(0, description)
  35.  
  36.  
  37.     def parseFile(self, fileName, fieldTuple):
  38.         "Read CSV export file and parse it to a list"
  39.  
  40.         import csv
  41.  
  42.         try:
  43.             srcFile = csv.reader(open(fileName, 'r'), delimiter=',')
  44.  
  45.             for row in srcFile:
  46.                 resultRow = []
  47.                 for i in fieldTuple:
  48.                     resultRow.append(row[i])
  49.                 self.list.append(resultRow)
  50.  
  51.         except IOError:
  52.             print "IOError Exiting..."
  53.             exit()
  54.  
  55.     def writeXLS(self, fileName):
  56.         "Write list to Excel compatible CSV file"
  57.  
  58.         try:
  59.             import csv
  60.             dstFile  = csv.writer(open(fileName, 'w'), dialect='excel')
  61.             for item in self.list:
  62.                 dstFile.writerow(item)
  63.  
  64.         except IOError:
  65.             print "IOError Exiting..."
  66.             exit()
  67.  
  68. if __name__ == "__main__":
  69.    
  70.     import sys
  71.  
  72.     if len(sys.argv) != 3:
  73.         print "Usage: python sgfilter.py <src file> <dst file>"
  74.  
  75.     else:
  76.         sg = ParseSGExport()
  77.         sg.parseFile(sys.argv[1], resultFields)
  78.         sg.unique()
  79.         sg.sort()
  80.         sg.writeXLS(sys.argv[2])