[英]PyParsing not behaving as expected with nested grammar
我有一個關於嵌套語法的問題。 你如何讓 pyparsing 尋找嵌套的語法結構。
from pyparsing import Word, alphas, alphanums, Suppress, LineEnd, LineStart, nums, Or, Group, OneOrMore, Literal, CaselessLiteral, Combine, Optional
word = Word(alphanums+'_')
object_type = Suppress("object ")+word.setResultsName("object_type")+Suppress('{')+LineEnd()
point = Literal('.')
e = CaselessLiteral('E')
plusorminus = Literal('+') | Literal('-')
number = Word(nums)
integer = Combine( Optional(plusorminus) + number )
floatnumber = Combine( integer +
Optional( point + Optional(number) ) +
Optional( e + integer )
)
attribute = word.setResultsName("attribute")
value = Or([floatnumber, word]).setResultsName("value")
attributes = Group(attribute+value+Suppress(";")+LineEnd())
namespace = Group(object_type+\ OneOrMore(attributes).setResultsName("attributes") + Suppress("}"))
all = OneOrMore(namespace).setResultsName("namespaces")
result = all.parseString(glm)
for n in result.namespaces:
print(n)
以下是我想解析的示例。 第一個命名空間按預期工作。 然而,第二個無法解析。 誰能解釋我缺少什么?
"""object object_type1{
attr1 0.0111;
name name_of_object_1;
}
object object_type1{
attr1 0.02;
name name_of_object_2;
object object_type2{
name name_of_object_3;
}
}
"""
要定義遞歸文法,即,一個術語本身是其定義的一部分,您需要使用 pyparsing 的Forward
類。 在您的情況下, namespace
可以包含屬性或嵌套命名空間。 為此,您首先必須為namespace
定義一種占位符:
namespace = Forward()
然后當需要定義內容(包括namespace
作為定義的一部分)時,使用<<=
運算符而不是=
:
namespace <<= Group(object_type + OneOrMore(attributes|namespace).setResultsName("attributes") + Suppress("}"))
all = OneOrMore(namespace).setResultsName("namespaces")
除此之外,您的解析器應該可以正常工作。
還有一些其他提示:
我最近添加了pprint()
方法來簡化列出 ParseResults 對象的內容。 嘗試result.pprint()
而不是您現在使用的 for 循環。
您實際上並不需要輸出中的換行符,因此將所有LineEnd()
術語替換為LineEnd().suppress()
- 這將使您的結果LineEnd().suppress()
。
在這種情況下,我不確定結果名稱是否真的對您有用。 但我發現使用expr("name")
比expr.setResultsName("name")
更具可讀性。 但任何一種形式都可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.