from lepl import * from lepl.graph import SimpleWalker class Table(Node): pass class Variable(Node): pass class Value(Node): pass class Query(Node): pass class Logical(Node): pass class Boolean(Node): pass class Statement(Node): pass statement = Delayed() logicalstatement = Delayed() booleanstatement = Delayed() number = Digit()[1:,...] variable = Regexp(r'[a-zA-Z][a-zA-Z0-9]*') > Variable table = Regexp(r'[a-zA-Z][a-zA-Z0-9]*') > Table string = Regexp(r'[\s\w\d]*') spaces = Drop(Regexp(r'\s*')) with Separator(spaces): value = number | '"' & string & '"' > Value term = value | variable booleanstatement += (statement & '&' & booleanstatement) | (statement & '|' & booleanstatement) | statement > Boolean logicalstatement += term & Any('<>=~') & logicalstatement | term > Logical statement += '(' & booleanstatement & ')' | logicalstatement query = table & '?' & booleanstatement > Query parser = query.parse_string ast = parser("materials ? 30 < shearmodulus < 50 & meltingtemp > 460 & (tensilestrength > 4000 | poissonsmodulus < 14)") # print parser("objects ? name ~ \"bicycle\" ")[0] # print SimpleWalker(ast) # print "Table is '%s'" % ast[0].Table[0] table = ast[0].Table[0][0] print "Searching table structure '%s'" % table matchneeded = False value1 = 0 value2 = 0 comparator = 0 logic = " AND " def extr(a): global matchneeded global value1 global value2 global comparator global logic s = "" for child in a: if type(child) in (Boolean, Logical, Statement): s += extr(child) elif type(child) in (Variable, Value): if matchneeded: value2 = child[0] matchneeded = False s += " %s ( %s %s %s ) " % (logic, value1, comparator, value2) value1 = value2 else: value1 = child[0] elif child == '&': logic = " AND " elif child == '|': logic = " OR " elif child in ('<', '>', '~', '='): matchneeded = True comparator = child elif child in ('(', ')'): s += child else: print "Unrecognized token: '%s'" % child return s print "arr: " + extr(ast[0].Boolean[0]) # print [child for child in ast[0].Boolean[0]]