我正在研究一种语法来解析搜索查询(不是对它们求值,只是将它们分解成组件)。现在我正在使用nestedExpr
,只是为了获取每个术语的不同“级别”,但是如果术语的第一部分是双引号的,我似乎有一个问题。在
简单的语法:
QUOTED = QuotedString(quoteChar = '“', endQuoteChar = '”', unquoteResults = False).setParseAction(remove_curlies)
WWORD = Word(alphas8bit + printables.replace("(", "").replace(")", ""))
WORDS = Combine(OneOrMore(dblQuotedString | QUOTED | WWORD), joinString = ' ', adjacent = False)
TERM = OneOrMore(WORDS)
NESTED = OneOrMore(nestedExpr(content = TERM))
query = '(dog* OR boy girl w/3 ("girls n dolls" OR friends OR "best friend" OR (friends w/10 enemies)))'
调用NESTED.parseString(query)
返回:
第一个dblQuotedString
实例在同一个嵌套中与术语的其余部分分开,第二个dblQuotedString
实例不会出现这种情况,如果被引用的位是QUOTED
实例(带有花引号),而不是带有直引号的dblQuotedString
,则也不会发生。在
关于dblQuotedString
有什么特别的地方我没有吗?在
注意:我知道operatorPrecedence
可以像这样分解搜索词,但是我对可以拆分的内容有一些限制,所以我正在测试是否可以使用nestedExpr
在这些限制内工作。在
nestedExpr
接受一个可选的关键字参数ignoreExpr
,以接受一个表达式,nestedExpr
应使用该表达式忽略否则将被解释为嵌套的开始符或闭包符的字符,默认值是pyparsing的quotedString
,它被定义为sglQuotedString | dblQuotedString
。这是为了处理如下字符串:由于默认的
ignoreExpr
是quotedString
,引号中的“)”不会被误解为右括号。在但是,
^{pr2}$content
参数也与dblQuotedString
匹配。前引号字符串由nestedExpr
在内部匹配,方法是跳过可能包含“()”s的带引号的字符串,然后匹配内容,这也匹配带引号的字符串。可以使用NoMatch
来抑制nestedExpr
的ignore表达式:现在应该可以给你:
您可以在https://pythonhosted.org/pyparsing/pyparsing-module.html#nestedExpr找到更多细节和示例
相关问题 更多 >
编程相关推荐