Pyparsing problem with operators

随声附和 提交于 2019-12-04 12:21:53
PaulMcG

One way to address your problem is to define AND as an Optional operator. If you do this, you'll have to take extra care that real keywords like 'and' and 'or' aren't misinterpreted as search words. Also, with Optional, you can add a default string, so that even if the "and" is missing in the original search query, your parsed text will insert it for you (for easier post-parse processing).

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)

Gives:

[[['word', 'and', 'ward'], 'or', 'wird']]
[[['word', 'and', 'werd'], 'or', 'wurd']]
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!