python – 运算符的Pyparsing问题
作者:互联网
我做了一个带有pyparsing的语法,我有一个问题.
语法试图解析搜索查询(使用运算符优先级,括号等),我需要空格像和运算符一样工作.
例如,这工作正常:
(word and word) or word
但这失败了:
(word word) or word
我希望第二个查询像第一个查询一样工作.
我的实际语法是:
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()
解决方法:
解决问题的一种方法是将AND定义为Optional运算符.如果你这样做,你必须格外小心,真正的关键词如“和”和“或”不会被误解为搜索词.此外,使用Optional,您可以添加默认字符串,这样即使原始搜索查询中缺少“和”,您的解析文本也会为您插入(以便于解析后处理).
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']]
标签:pyparsing,python 来源: https://codeday.me/bug/20190827/1737172.html