Python (pyparsing): parsing legacy curly braces file format

I have to parse with Python (pyparse) a legacy file format that is not well defined.

It is of the curly brace family (im fact, having to parse arbitrary curly brace formats is a recurring issue because people are always like “XML is too verbose, let’s invent our own format”).

So I have things like

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Variable = [1, 2]
Variable2 = {
Variable,
"Literal",
}
Variable[1] = Variable2
Namespace::Function(argument, {"string literal",
100})
</code>
<code>Variable = [1, 2] Variable2 = { Variable, "Literal", } Variable[1] = Variable2 Namespace::Function(argument, {"string literal", 100}) </code>
Variable = [1, 2]
Variable2 = {
   Variable,
   "Literal",
}

Variable[1] = Variable2

Namespace::Function(argument, {"string literal",
100})

Newlines are significant outside of expressions (separating statements like ; does in C) but not significant in any kind of braces ({}, () and []).

To make sense of it, it needs to be parsed such that:

  1. Each line is a child of the root of the AST (where “line” refers to lines delimited by line breaks not inside any kind of braces).
  2. Each kind of parentheses constitutes a node (annotated with the type of parentheses).
  3. The children of a parenthesis list are comma separated (in this sense newlines also constitute a kind of brace).
  4. Anything else is treated as a single token to be handled in another pass.

So for the above example the AST should look like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Root
* Brace: n
* Token: 'Variable ='
* Brace: []
* Token: '1'
* Token: '2'
* Brace: n
* Token: 'Variable2 ='
* Brace: {}
* Token: 'Variable'
* Token: '"Literal"'
* Brace: n
* Token: 'Variable'
* Brace: []
* Token: '1'
* Token: '= Variable2'
* Brace: n
* Token: 'Namespace:Function'
* Brace: ()
* Token: 'argument'
* Brace: {}
* Token: '"string literal"'
* Token: '100'
</code>
<code>Root * Brace: n * Token: 'Variable =' * Brace: [] * Token: '1' * Token: '2' * Brace: n * Token: 'Variable2 =' * Brace: {} * Token: 'Variable' * Token: '"Literal"' * Brace: n * Token: 'Variable' * Brace: [] * Token: '1' * Token: '= Variable2' * Brace: n * Token: 'Namespace:Function' * Brace: () * Token: 'argument' * Brace: {} * Token: '"string literal"' * Token: '100' </code>
Root
 * Brace: n
   * Token: 'Variable ='
   * Brace: []
     * Token: '1'
     * Token: '2'
 * Brace: n
   * Token: 'Variable2 ='
   * Brace: {}
     * Token: 'Variable'
     * Token: '"Literal"'
 * Brace: n
   * Token: 'Variable'
   * Brace: []
     * Token: '1'
   * Token: '= Variable2'
 * Brace: n
   * Token: 'Namespace:Function'
     * Brace: ()
       * Token: 'argument'
       * Brace: {}
         * Token: '"string literal"'
         * Token: '100'

Represented in Python as something like:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>[
Brace('n', [
'Variable =',
Brace('[]', ['1', '2'])
]),
...
</code>
<code>[ Brace('n', [ 'Variable =', Brace('[]', ['1', '2']) ]), ... </code>
[
  Brace('n', [
    'Variable =',
    Brace('[]', ['1', '2'])
  ]),
  ...

The issues are

  1. Specifying the syntax for the parser,
  2. Converting the result from the parser into a data structure that I can use afterwards.

(I used a dedicated parser package that did (1), but the result was (2) completely unusable for any further steps, so I’m trying again, this time with pyparsing.)

1

Parsing Curly Basic Formats with ‘pyparsing’:

  1. Define The Grammer: Use pyparsing to create rules for handling variables, literals, different types of brackets ('[]','{}','()'). Use nestedExpr for nested structures.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>from pyparsing import Word, alphas, nums, nestedExpr, quotedString, Group, ZeroOrMore, LineEnd
identifier = Word(alphas + "_", alphas + nums + "_")
literal = quotedString
square_braces = nestedExpr('[', ']', content=identifier | literal)
curly_braces = nestedExpr('{', '}', content=identifier | literal | square_braces)
parentheses = nestedExpr('(', ')', content=identifier | curly_braces)
statement = Group(identifier + '=' + (square_braces | curly_braces | parentheses))
grammar = ZeroOrMore(statement + LineEnd().suppress())
</code>
<code>from pyparsing import Word, alphas, nums, nestedExpr, quotedString, Group, ZeroOrMore, LineEnd identifier = Word(alphas + "_", alphas + nums + "_") literal = quotedString square_braces = nestedExpr('[', ']', content=identifier | literal) curly_braces = nestedExpr('{', '}', content=identifier | literal | square_braces) parentheses = nestedExpr('(', ')', content=identifier | curly_braces) statement = Group(identifier + '=' + (square_braces | curly_braces | parentheses)) grammar = ZeroOrMore(statement + LineEnd().suppress()) </code>
from pyparsing import Word, alphas, nums, nestedExpr, quotedString, Group, ZeroOrMore, LineEnd

identifier = Word(alphas + "_", alphas + nums + "_")
literal = quotedString

square_braces = nestedExpr('[', ']', content=identifier | literal)
curly_braces = nestedExpr('{', '}', content=identifier | literal | square_braces)
parentheses = nestedExpr('(', ')', content=identifier | curly_braces)

statement = Group(identifier + '=' + (square_braces | curly_braces | parentheses))
grammar = ZeroOrMore(statement + LineEnd().suppress())
  1. Convert To AST: Use parse actions to build an Abstract Syntax Tree (AST). Define a Brace class to represent a different brace types.
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class Brace:
def __init__(self, brace_type, children):
self.brace_type = brace_type
self.children = children
def create_ast_node(tokens):
return Brace(tokens[0], tokens[1:])
statement.setParseAction(create_ast_node)
</code>
<code>class Brace: def __init__(self, brace_type, children): self.brace_type = brace_type self.children = children def create_ast_node(tokens): return Brace(tokens[0], tokens[1:]) statement.setParseAction(create_ast_node) </code>
class Brace:
    def __init__(self, brace_type, children):
        self.brace_type = brace_type
        self.children = children

def create_ast_node(tokens):
    return Brace(tokens[0], tokens[1:])

statement.setParseAction(create_ast_node)
  1. Example Usage:

Parse your input and generate as AST

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>input_text = """
Variable = [1, 2]
Variable2 = {
Variable,
"Literal",
}
"""
result = grammar.parseString(input_text)
print(result)
</code>
<code>input_text = """ Variable = [1, 2] Variable2 = { Variable, "Literal", } """ result = grammar.parseString(input_text) print(result) </code>
input_text = """
Variable = [1, 2]
Variable2 = {
   Variable,
   "Literal",
}
"""
result = grammar.parseString(input_text)
print(result)

This approach efficiently parses custom brace formats and organizes the output into a structured, usable form. I hope my definition helps!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật