[英]Pyparsing problem with operators
我做了一個帶有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']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.