簡體   English   中英

將BNF語法轉換為pyparsing

[英]Convert BNF grammar to pyparsing

如何使用正則表達式(或pyparsing更好?)來描述下面提供的腳本語言(Backus-Naur Form):

<root>   :=     <tree> | <leaves>
<tree>   :=     <group> [* <group>] 
<group>  :=     "{" <leaves> "}" | <leaf>;
<leaves> :=     {<leaf>;} leaf
<leaf>   :=     <name> = <expression>{;}

<name>          := <string_without_spaces_and_tabs>
<expression>    := <string_without_spaces_and_tabs>

腳本示例:

{
 stage = 3;
 some.param1 = [10, 20];
} *
{
 stage = 4;
 param3 = [100,150,200,250,300]
} *
 endparam = [0, 1]

我使用python re.compile並希望將所有內容分組,如下所示:

[ [ 'stage',       '3'],
  [ 'some.param1', '[10, 20]'] ],

[ ['stage',  '4'],
  ['param3', '[100,150,200,250,300]'] ],

[ ['endparam', '[0, 1]'] ]

更新:我發現pyparsing是更好的解決方案,而不是正則表達式。

Pyparsing允許您簡化這些類型的構造

leaves :: {leaf} leaf

只是

OneOrMore(leaf)

所以你的BNF在pyparsing中的一種形式看起來像:

from pyparsing import *

LBRACE,RBRACE,EQ,SEMI = map(Suppress, "{}=;")
name = Word(printables, excludeChars="{}=;")
expr = Word(printables, excludeChars="{}=;") | quotedString

leaf = Group(name + EQ + expr + SEMI)
group = Group(LBRACE + ZeroOrMore(leaf) + RBRACE) | leaf
tree = OneOrMore(group)

我加入quotedString作為替代expr的,如果你想擁有的東西, 包括排除字符之一。 並且在葉子和組周圍添加組將保持支撐結構。

不幸的是,您的樣本並不完全符合此BNF:

  1. [10, 20][0, 1] [10, 20]空格使它們成為無效的exprs

  2. 有些葉子沒有終止; 小號

  3. 孤獨的*字符 - ???

此示例使用上述解析器成功解析:

sample = """
{
 stage = 3;
 some.param1 = [10,20];
}
{
 stage = 4;
 param3 = [100,150,200,250,300];
}
 endparam = [0,1];
 """

parsed = tree.parseString(sample)    
parsed.pprint()

贈送:

[[['stage', '3'], ['some.param1', '[10,20]']],
 [['stage', '4'], ['param3', '[100,150,200,250,300]']],
 ['endparam', '[0,1]']]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM