Skip to content

Instantly share code, notes, and snippets.

@zed
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zed/c5f707430aa5e7d65c23 to your computer and use it in GitHub Desktop.
Save zed/c5f707430aa5e7d65c23 to your computer and use it in GitHub Desktop.
#!/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