Pyparsing:dblQuotedString在nestedExp中的解析方式不同

2024-09-30 18:14:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究一种语法来解析搜索查询(不是对它们求值,只是将它们分解成组件)。现在我正在使用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)返回:

^{2}$

第一个dblQuotedString实例在同一个嵌套中与术语的其余部分分开,第二个dblQuotedString实例不会出现这种情况,如果被引用的位是QUOTED实例(带有花引号),而不是带有直引号的dblQuotedString,则也不会发生。在

关于dblQuotedString有什么特别的地方我没有吗?在

注意:我知道operatorPrecedence可以像这样分解搜索词,但是我对可以拆分的内容有一些限制,所以我正在测试是否可以使用nestedExpr在这些限制内工作。在


Tags: or实例false语法queryreplacenested术语
1条回答
网友
1楼 · 发布于 2024-09-30 18:14:59

nestedExpr接受一个可选的关键字参数ignoreExpr,以接受一个表达式,nestedExpr应使用该表达式忽略否则将被解释为嵌套的开始符或闭包符的字符,默认值是pyparsing的quotedString,它被定义为sglQuotedString | dblQuotedString。这是为了处理如下字符串:

(this has a tricky string "string with )" )

由于默认的ignoreExprquotedString,引号中的“)”不会被误解为右括号。在

但是,content参数也与dblQuotedString匹配。前引号字符串由nestedExpr在内部匹配,方法是跳过可能包含“()”s的带引号的字符串,然后匹配内容,这也匹配带引号的字符串。可以使用NoMatch来抑制nestedExpr的ignore表达式:

^{pr2}$

现在应该可以给你:

[['dog* OR boy girl w/3',
 ['"girls n dolls" OR friends OR "best friend" OR', ['friends w/10 enemies']]]]

您可以在https://pythonhosted.org/pyparsing/pyparsing-module.html#nestedExpr找到更多细节和示例

相关问题 更多 >