Grammar parsing code
Python
code posted
by
Andy Norris
created at 01 Dec 19:34, updated at 02 Dec 13:17
Edit
|
Back
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
def parse(element,text): tokens = text.split() tokens.reverse() return rec_parse(element,tokens) def rec_parse(element,tokens): for path in grammar[element]: elements = [element] item = None valid = True for word in path: if tokens[-1] == word: item = tokens.pop() elif word in grammar: item = rec_parse(word,tokens) if item != None:ss elements.append(item) else: valid = False break if valid: return elements return None def parse_s(text): return parse('S', text) |
593 Bytes in 2 ms with coderay