Last active
August 29, 2015 14:22
-
-
Save zed/c5f707430aa5e7d65c23 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
http://ru.stackoverflow.com/q/427088/23044 | |
""" | |
import grako # $ pip install grako | |
grammar_ebnf = """ | |
record = type name teacher auditory $ ; | |
type = "pr." | "lab." | "c." ; | |
name = { word }+ ; | |
teacher = abbr word ; | |
auditory = /[0-9]{3}/ ; | |
(* add negative lookahead for the dot to avoid matching start of the abbr *) | |
word = { CHAR }+ !/\./; | |
abbr = CHAR [ CHAR ] /\./ ; | |
CHAR = /[a-zA-Z]/ ; | |
""" | |
class Semantics: | |
def name(self, ast): | |
return ' '.join(ast) | |
def teacher(self, ast): | |
return ' '.join(ast) | |
def auditory(self, ast): | |
return int(ast) | |
def word(self, ast): | |
return ''.join(ast) | |
def abbr(self, ast): | |
return ''.join(ast) | |
model = grako.genmodel("Record", grammar_ebnf) | |
ast = model.parse("lab. Subject name Au. Diachin 511", "record", | |
semantics=Semantics()) | |
from pprint import pprint | |
pprint(dict(zip("type name teacher auditory".split(), ast))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment