#!/bin/python ################################################################################ # # ContextFreeGrammar- 3.23.09 - Joe Mariglio # #=============================================================================== # # produces cfg's using a grammar file with the format # 'rule' -> 'expansion_0' | 'expansion_1' ... | 'expansion_n' # currently prints to stdout but this could change... # ################################################################################ import sys, string, os.path, random, array, re contextRules = {} def addRule(rule, expansion): if rule in contextRules.keys(): contextRules[rule].append(expansion) else: contextRules[rule] = [expansion] def dump(rule): return rule + " -> " + str(contextRules[rule]) def iter_expand(current): if current not in contextRules.keys(): yield current else: toExpand = random.choice(contextRules[current]).split(" ") for item in toExpand: yield expand(item) def expand(current): return [i for i in iter_expand(current)] def iter_flatten(iterable): it = iter(iterable) for e in it: if isinstance(e, (list, tuple)): for f in iter_flatten(e): yield f else: yield e def flatten(signal): return [i for i in iter_flatten(signal)] def renderExpansion(expansion): out = "" expansion = flatten(expansion) for item in expansion: out += item + " " return out def parseFile(path): comment = re.compile(r'#.*$') rule = re.compile(r'(\w+) *-> *(.*)') exps = re.compile(r'\s*\|\s*') infile = open(path, "r") lines = infile.readlines() infile.close() for line in lines: line = comment.sub("", line) m = rule.search(line) if m: key = m.group(1) value = m.group(2) values = exps.split(m.group(2)) for value in values: addRule(key, value) def main(argv): if len(sys.argv) == 2: path = sys.argv[1] parseFile(path) print(renderExpansion(expand("S"))) else: print("wha?") if __name__ == '__main__': import sys, string, os.path, random, array, re main(sys.argv[1:])