I want to parse strings like alpha OR beta gamma
where a missing operator (in this case between beta
and gamma
a implicit AND
is used.
Here is the code I tried:
import pyparsing as pp
class Term:
def __init__(self, tokens: pp.ParseResults):
self.value = str(tokens[0])
def __repr__(self) -> str:
return f"Term({self.value})"
class BinaryOp:
def __init__(self, tokens: pp.ParseResults) -> None:
self.op = tokens[0][1]
self.left = tokens[0][0]
self.right = tokens[0][2]
def __repr__(self) -> str:
return f"BinaryOp({self.op}, {self.left}, {self.right})"
and_ = pp.Keyword("AND")
or_ = pp.Keyword("OR")
word = (~(and_ | or_) + pp.Word(pp.alphanums + pp.alphas8bit + "_")).set_parse_action(Term)
expression = pp.infix_notation(
word,
[
(pp.Optional(and_), 2, pp.opAssoc.LEFT, BinaryOp),
(or_, 2, pp.opAssoc.LEFT, BinaryOp),
],
)
input_string = "alpha OR beta gamma"
parsed_result = expression.parseString(input_string)
print(parsed_result.asList())
The output is [BinaryOp(OR, Term(alpha), Term(beta))]
, so the implicit AND
and gamma
is not parsed. How could I fix this?