#
# Created by Pedro Paulo de Magalhaes Oliveira Junior
# Jun, 08 at HBM 2008
# Convert multiple aseg files into an excel csv
# Questions: ppj at netfilter dot com dot br
#


import os
import sys
import getopt
import tokenize

ListaCasos = dict();

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "lh")
    except getopt.error, msg:
        usage(msg)
        return 2
    if not args:
        usage("at least one file argument is required")
        return 2
    listnames = 0
    for o, a in opts:
        if o == "-h":
            print __doc__
            return
        if o == "-l":
            listnames = 1
    exit = None
    for filename in args:
        x = process(filename, listnames)
        exit = exit or x
    header=0
    for LC,Caract in ListaCasos.iteritems():
        if header==0:
            print "Case ",
            for nome,val in Caract.iteritems():
                print nome,
            header=1
            print ""
        print LC,
        for nome,val in Caract.iteritems():
            print val,
    return exit

def usage(msg):
    sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
    sys.stderr.write("Usage: %s [-l] dir fileout...\n" % sys.argv[0])
    sys.stderr.write("Try `%s -h' for more information.\n" % sys.argv[0])

def process(filename, listnames):
    if os.path.isdir(filename):
        return processdir(filename, listnames)
    f=open(filename,"r")
    column = dict()
    for line in f:
        if (line[0]<>"#"):
            lll = line.split()
            column[lll[4]] = lll[3]
    ListaCasos[filename]=column

                 
def processdir(dir, listnames):
    try:
        names = os.listdir(dir)
    except os.error, msg:
        sys.stderr.write("Can't list directory: %s\n" % dir)
        return 1
    files = []
    for name in names:
        fn = os.path.join(dir, name)
        if os.path.normcase(fn).endswith("aseg.stats") or os.path.isdir(fn):
            files.append(fn)
    files.sort(lambda a, b: cmp(os.path.normcase(a), os.path.normcase(b)))
    exit = None
    for fn in files:
        x = process(fn, listnames)
        exit = exit or x     
    return exit

if __name__ == "__main__":
    sys.exit(main())

UserContributions/Scripts/ppaulo/excel-aseg (last edited 2008-08-01 10:38:08 by PedroOliveira)