def __init__(self, formal_rule): if not isinstance(formal_rule, str): raise ValueError("rule constructor given %s; requires a string", type(formal_rule)) self.formal_rule = formal_rule tokens = "(){}>,".split() for token in tokens: formal_rule = formal_rule.replace(token, " " + token + " ") formal_rule = formal_rule.split() self.from_const = constituent(formal_rule[0]) self.to_consts = map(lambda x: constituent(x), formal_rule[2:]) if formal_rule[1] != ">": raise ValueError("Malformed rule: %s", formal_rule)
def gen_random_sentence(self, lexicon): """generate a random sentence according to this grammar using the supplied lexicon """ tree = [constituent("S")] while any(map(lambda x: x not in self.terminals, tree)): next_tree = [] for const in tree: if const in self.terminals: next_tree.append(const) else: next_tree.extend(self.rules[const]) tree = next_tree return " ".join(random.choice(lexicon.by_cat[x]) for x in tree)