pyslha.py

Sun, 01 Aug 2010 01:14:45 +0200

author
Andy Buckley <andy@insectnation.org>
date
Sun, 01 Aug 2010 01:14:45 +0200
changeset 3
d52a5a633a6c
parent 1
dee5706ae812
child 4
ff16e3d891cd
permissions
-rw-r--r--

Adding case-insensitivity

andy@1 1 #! /usr/bin/env python
andy@1 2
andy@1 3 import re
andy@1 4
andy@1 5 class Block:
andy@1 6 def __init__(self, name):
andy@1 7 self.name = name
andy@1 8 self.entries = {}
andy@1 9
andy@1 10 def add_entry(self, entry):
andy@1 11 #print entry
andy@1 12 nextparent = self.entries
andy@1 13 if len(entry) < 2:
andy@1 14 raise Exception("Block entries must be at least a 2-tuple")
andy@1 15 for e in entry[:-2]:
andy@1 16 if e is not entry[-1]:
andy@1 17 nextparent = nextparent.setdefault(e, {})
andy@1 18 nextparent[entry[-2]] = entry[-1]
andy@1 19 #print self.entries
andy@1 20
andy@1 21 def __cmp__(self, other):
andy@1 22 return self.name < other.name
andy@1 23
andy@1 24 def __str__(self):
andy@1 25 s = self.name
andy@1 26 s += "\n"
andy@1 27 s += str(self.entries)
andy@1 28 return s
andy@1 29
andy@1 30
andy@1 31 class Decay:
andy@1 32 def __init__(self, pid, totalwidth):
andy@1 33 self.pid = totalwidth
andy@1 34
andy@1 35
andy@1 36 def readSpcFile(filename):
andy@1 37 ## TODO: Use new file handling from future
andy@1 38 blocks = {}
andy@1 39 decays = {}
andy@1 40 f = open(filename, "r")
andy@1 41 currentblock = None
andy@1 42 for l in f:
andy@1 43 line = l.strip()[:-1]
andy@1 44 ## Handle (ignore) comment lines
andy@1 45 if line.startswith("#"):
andy@1 46 continue
andy@1 47 if "#" in line:
andy@1 48 line = line[:line.index("#")]
andy@1 49
andy@1 50 ## Handle BLOCK/DECAY start lines
andy@3 51 if line.upper().startswith("BLOCK"):
andy@1 52 ##TODO: Deal with Q= entries
andy@3 53 blockname = line[5:].strip().upper()
andy@1 54 currentblock = blockname
andy@1 55 blocks[blockname] = Block(blockname)
andy@3 56 elif line.upper().startswith("DECAY"):
andy@1 57 currentblock = "DECAY"
andy@1 58 # TODO: particle details
andy@1 59 elif currentblock is not None:
andy@1 60 items = line.split()
andy@1 61 if len(items) < 2:
andy@1 62 continue
andy@1 63 # TODO: Sort out tuple item types: autoconvert integers and floats
andy@1 64 if currentblock != "DECAY":
andy@1 65 #print currentblock
andy@1 66 blocks[currentblock].add_entry(items)
andy@1 67 else:
andy@1 68 #print "NOT HANDLING DECAYS YET!"
andy@1 69 pass
andy@1 70
andy@1 71 f.close()
andy@1 72 return blocks, decays
andy@1 73
andy@1 74
andy@1 75 if __name__ == "__main__":
andy@1 76 import sys
andy@1 77 for a in sys.argv[1:]:
andy@1 78 blocks, decays = readSpcFile(a)
andy@3 79
andy@3 80 # for bname, b in sorted(blocks.iteritems()):
andy@3 81 # print b
andy@3 82 # print
andy@3 83
andy@3 84 print blocks["MASS"].entries["25"]

mercurial