Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A recursive descent parser is a simple form of parser that can parse many grammars. While the entire theory of parsing is too large for a stack-overflow answer, the most common approach to parsing involves two steps: first, tokenisation, which extracts subwords of your string (here, probably words like 'Root', and 'ABC', or brackets like '(' and ')'), and then parsing using recursive functions.</p> <p>This code parses input (like your example), producing a so-called parse tree, and also has a function 'show_children' which takes the parse tree, and produces the children view of the expression as your question asked.</p> <pre><code>import re class ParseError(Exception): pass # Tokenize a string. # Tokens yielded are of the form (type, string) # Possible values for 'type' are '(', ')' and 'WORD' def tokenize(s): toks = re.compile(' +|[A-Za-z]+|[()]') for match in toks.finditer(s): s = match.group(0) if s[0] == ' ': continue if s[0] in '()': yield (s, s) else: yield ('WORD', s) # Parse once we're inside an opening bracket. def parse_inner(toks): ty, name = next(toks) if ty != 'WORD': raise ParseError children = [] while True: ty, s = next(toks) if ty == '(': children.append(parse_inner(toks)) elif ty == ')': return (name, children) # Parse this grammar: # ROOT ::= '(' INNER # INNER ::= WORD ROOT* ')' # WORD ::= [A-Za-z]+ def parse_root(toks): ty, _ = next(toks) if ty != '(': raise ParseError return parse_inner(toks) def show_children(tree): name, children = tree if not children: return print '%s -&gt; %s' % (name, ' '.join(child[0] for child in children)) for child in children: show_children(child) example = '( Root ( AB ( ABC ) ( CBA ) ) ( CD ( CDE ) ( FGH ) ) )' show_children(parse_root(tokenize(example))) </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