Pyparsing problem with operators

I made a grammar with pyparsing and I have a problem. The grammar is trying to parse the search query (with operator precedence, parenthesis, etc.), and I need the spaces to work with both the operator and the operator.

For example, this works great:

(word and word) or word

But this fails:

(word word) or word

And I want the second request to work as the first.

My actual grammar:

WWORD = printables.replace("(", "").replace(")", "")
QUOTED = quotedString.setParseAction(removeQuotes)

OAND = CaselessLiteral("and")
OOR = CaselessLiteral("or")
ONOT = "-"

TERM = (QUOTED | WWORD)

EXPRESSION = operatorPrecedence(TERM,
    [
        (ONOT, 1, opAssoc.RIGHT),
        (OAND, 2, opAssoc.LEFT),
        (OOR, 2, opAssoc.LEFT)
    ])

STRING = OneOrMore(EXPRESSION) + StringEnd()
+3
source share
1 answer

- AND . , , "" "" . , "" , "" , ( ).

from pyparsing import *

QUOTED = quotedString.setParseAction(removeQuotes)  
OAND = CaselessLiteral("and") 
OOR = CaselessLiteral("or") 
ONOT = Literal("-")
WWORD = ~OAND + ~OOR + ~ONOT + Word(printables.replace("(", "").replace(")", ""))
TERM = (QUOTED | WWORD)  
EXPRESSION = operatorPrecedence(TERM,
    [
    (ONOT, 1, opAssoc.RIGHT),
    (Optional(OAND,default="and"), 2, opAssoc.LEFT),
    (OOR, 2, opAssoc.LEFT)
    ])

STRING = OneOrMore(EXPRESSION) + StringEnd()

tests = """\
word and ward or wird
word werd or wurd""".splitlines()

for t in tests:
    print STRING.parseString(t)

:

[[['word', 'and', 'ward'], 'or', 'wird']]
[[['word', 'and', 'werd'], 'or', 'wurd']]
+6

Source: https://habr.com/ru/post/1793430/


All Articles