#!/usr/bin/python import os, sys, xml.dom.minidom a = '\(\(\(1/\(4959476121600 a1^7 a2^7 r^2\)\)\((-r^14 + 14 a1^13 heavi[a1-5*a2-r^2]^2 )\)\)\)' # Convert the brackets into XML tokens a = a.replace(r'\(','\n') a = a.replace(r'\)','\n') a = a.replace('(','\n') a = a.replace(')','\n') # Enclose the document a = '\n'+a+'\n\n' # Parse the XML document dom = xml.dom.minidom.parseString(a) def convert_node_to_strlist(dom): try: #print "tagName=",dom.tagName dom.tagName except: None a = [] for d in dom.childNodes: if d.nodeType == d.TEXT_NODE: t = str(d.data).strip() if len(t): a += [t] else: a += convert_node_to_strlist(d) return a m = convert_node_to_strlist(dom) #print m if len(m) != 3 and len(m) != 4: raise def extract_nom_denom(m): if len(m) == 3: if m[0] == '1/': nom = m[2] denom = m[1] elif m[1] == '/': nom = m[0] denom = m[2] else: raise elif len(m) == 4: if m[0] == '-' and m[1] == '1/': denom = m[0]+m[2] nom = m[3] else: raise return nom, denom nom,denom = extract_nom_denom(m) a = nom a = a.replace(' + ', '\n+') a = a.replace(' - ', '\n-') # Make sure the first token is a signed integer coefficient q = [] a0 = a.split('\n') for a in a0: if len(a) == 0: continue #print "<<", a b = a.split() test_int = 1 #print "|" try: c = int(b[0]) except: test_int = 0 if test_int: repl = '%+d %s' % ( c, ' '.join(b[1:])) else: w = b[0] if w[0] == '+': c = 1 w = ''.join(list(w[1:])) elif w[0] == '-': c = -1 w = ''.join(list(w[1:])) else: c = 1 repl = '%+d %s %s' % ( c, w, ' '.join(b[1:])) #print '>>', repl q += [repl] a = '\n'.join(q) token='heavi' # Pad the powers pad=2 b0 = [] a0 = a.split('\n') for l in a0: #print 'l=',l o0 = [] l0 = l.split() #print 'l0=',l0 for w in l0: s = w.split('^') # This is an ordinary word if len(s) == 1: o = w # This is a power elif len(s) == 2: bs = s[0] pw = int(s[1]) if bs.find(token) == 0: if pw == 0: raise o = bs else: pw = "%0*d" % ( pad, pw ) o = bs+'^'+pw else: print "A. Shirokov: The error occurs with 'raise' in line 154" print " but Python does not report the line number correctly, by only saying 'File \"./debracket.py\", line 91'" print " The stack of error messages may have some problem" print "----------------------------------------------------------------" raise o0 += [o] b0 += [ ' '.join(o0) ] a = '\n'.join(b0); print "Done3" fh = file(fb,"w") fh.write(a) fh.close() print "Done4"