Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><em>Recursivity</em> is the key here. Try something around that:</p> <pre><code>def parse(it): result = [] while True: try: tk = next(it) except StopIteration: break if tk == '}': break val = next(it) if val == '{': result.append((tk,parse(it))) else: result.append((tk, val)) return result </code></pre> <p>The use case:</p> <pre><code>import pprint data = """ Continent { Name Europe Country { Name UK Dog { Name Fiffi Colour Gray } Dog { Name Smut Colour Black } } } """ r = parse(iter(data.split())) pprint.pprint(r) </code></pre> <p>... which produce (Python 2.6):</p> <pre><code>[('Continent', [('Name', 'Europe'), ('Country', [('Name', 'UK'), ('Dog', [('Name', 'Fiffi'), ('Colour', 'Gray')]), ('Dog', [('Name', 'Smut'), ('Colour', 'Black')])])])] </code></pre> <p>Please take this as only starting point, and feel free to improve the code as you need (depending on your data, a dictionary could have been a better choice, maybe). In addition, the sample code does not handle properly ill formed data (notably extra or missing <code>}</code> -- I urge you to do a full test coverage ;)</p> <hr> <p><strong>EDIT:</strong> Discovering <code>pyparsing</code>, I tried the following which appears to work (much) better and could be (more) easily tailored for special needs:</p> <pre><code>import pprint from pyparsing import Word, Literal, Forward, Group, ZeroOrMore, alphas def syntax(): lbr = Literal( '{' ).suppress() rbr = Literal( '}' ).suppress() key = Word( alphas ) atom = Word ( alphas ) expr = Forward() pair = atom | (lbr + ZeroOrMore( expr ) + rbr) expr &lt;&lt; Group ( key + pair ) return expr expr = syntax() result = expr.parseString(data).asList() pprint.pprint(result) </code></pre> <p>Producing:</p> <pre><code>[['Continent', ['Name', 'Europe'], ['Country', ['Name', 'UK'], ['Dog', ['Name', 'Fiffi'], ['Colour', 'Gray']], ['Dog', ['Name', 'Smut'], ['Colour', 'Black']]]]] </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload