"MooMaster" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > I'm trying to develop a little script that does some string > manipulation. I have some few hundred strings that currently look like > this: > > cond(a,b,c) > > and I want them to look like this: > > cond(c,a,b)
<snip> Pyparsing makes this a fairly tractable problem. The hardest part is defining the valid contents of a relational and arithmetic expression, which may be found within the arguments of your cond(a,b,c) constructs. Not guaranteeing this 100%, but it did convert your pathologically nested example on the first try. -- Paul ---------- from pyparsing import * ident = ~Literal("cond") + Word(alphas) number = Combine(Optional("-") + Word(nums) + Optional("." + Word(nums))) arithExpr = Forward() funcCall = ident+"("+delimitedList(arithExpr)+")" operand = number | funcCall | ident binop = oneOf("+ - * /") arithExpr << ( ( operand + ZeroOrMore( binop + operand ) ) | ("(" + arithExpr + ")" ) ) relop = oneOf("< > == <= >= != <>") condDef = Forward() simpleCondExpr = arithExpr + ZeroOrMore( relop + arithExpr ) | condDef multCondExpr = simpleCondExpr + "*" + arithExpr condExpr = Forward() condExpr << ( simpleCondExpr | multCondExpr | "(" + condExpr + ")" ) def reorderArgs(t): return "cond(" + ",".join(["".join(t.arg3), "".join(t.arg1), "".join(t.arg2)]) + ")" condDef << ( Literal("cond") + "(" + Group(condExpr).setResultsName("arg1") + "," + Group(condExpr).setResultsName("arg2") + "," + Group(condExpr).setResultsName("arg3") + ")" ).setParseAction( reorderArgs ) tests = [ "cond(a,b,c)", "cond(1>2,b,c)", "cond(-1,1,f)*((float(e)*(2**4))+(float(d)*8)+(float(c)*4)+(float(b)*2)+floa t(a))", "cond(a,b,(abs(c) >= d))", "cond(0,cond(c,cond(e,cond(g,h,(a<f)),(a<d)),(a<b)),(a<1))", ] for t in tests: print t,"->",condExpr.transformString(t) ---------- Prints: cond(a,b,c) -> cond(c,a,b) cond(1>2,b,c) -> cond(c,1>2,b) cond(-1,1,f)*((float(e)*(2**4))+(float(d)*8)+(float(c)*4)+(float(b)*2)+float (a)) -> cond(f,-1,1)*((float(e)*(2**4))+(float(d)*8)+(float(c)*4)+(float(b)*2)+float (a)) cond(a,b,(abs(c) >= d)) -> cond((abs(c)>=d),a,b) cond(0,cond(c,cond(e,cond(g,h,(a<f)),(a<d)),(a<b)),(a<1)) -> cond((a<1),0,cond((a<b),c,cond((a<d),e,cond((a<f),g,h)))) -- http://mail.python.org/mailman/listinfo/python-list