Last active
July 21, 2018 21:13
-
-
Save amontalenti/eed3becfe810a817235d 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
from itertools import chain, product | |
from re import match, findall | |
GRAMMAR = ''' | |
<sentence> ::= <noun phrase=""> <verb phrase=""> | |
<noun> ::= "boy " | "troll " | "moon " | "telescope " | |
<transitive verb=""> ::= "hits " | "sees " | |
<intransitive verb=""> ::= "runs " | "sleeps " | |
<adjective> ::= "big " | "red " | |
<adverb> ::= "quickly " | "quietly " | |
<determiner> ::= "a " | "that " | "each " | "every " | |
<pronoun> ::= "he " | "she " | "it " | |
<noun phrase=""> ::= <determiner> <noun> | <determiner> <adjective> <noun> | |
<verb phrase=""> ::= <intransitive verb=""> | <transitive verb=""> <noun phrase=""> | |
''' | |
def parse(g): | |
return dict([(w.strip(), [findall(r'(<.+?>|".+?")', s) | |
for s in m.split('|')]) | |
for w, m in [d.split('::=') | |
for d in g.strip().splitlines()]]) | |
def generate(term): | |
val = findall(r'"(.*?)"', term) \ | |
if match('".*', term) \ | |
else chain(*[map(''.join, product(*map(generate, p))) | |
for p in syntax[term]]) | |
return val | |
syntax = parse(GRAMMAR) | |
print list(generate('<sentence>')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment