import yaml, web class Answer: def __init__(self): self.question = None self.answer = "" self.to = None def __str__(self): return "%s -> %s\n" % (self.answer, self.to.code) class Question: def __init__(self): self.index = "" self.question = "" self.answers = [] self.parent = None self.code = None self.help = "" def __str__(self): if self.parent: pidx = self.parent.index else: pidx = "(first)" s = "%s (%s) <- %s\n" % (self.question[:20].strip(), self.index, pidx) for a in self.answers: s += " " + str(a) return s if __name__ == "__main__": fp = open("questions.yaml") y = yaml.load(fp) QUESTIONS = {} # build questions list for item in y.items(): q = Question() q.code, dic = item q.question = dic["question"] if dic.has_key("help"): q.help = dic["help"] for itema in dic.get("answers", []): a = Answer() a.question = q a.answer = itema["answer"] a.to = itema["destination"] # string q.answers.append(a) QUESTIONS[q.code] = q # walk through and set answer.to, parent for code, question in QUESTIONS.items(): for answer in question.answers: answer.to = QUESTIONS[answer.to] answer.to.parent = answer.question # walk through and set index def set_index(question, index): question.index = index count = 1 for a in question.answers: set_index(a.to, "%s%s" % (index, count)) count += 1 set_index(QUESTIONS["q1"], "1") # now generate HTML template = web.template.frender('template.html') for q in QUESTIONS.values(): print "Question %s" % q.code answers = [(a.answer, a.to.index) for a in q.answers] if not q.parent: answer_to = None else: answer_to = [a for a in q.parent.answers if a.to.index == q.index][0] chain = [] thisq = q while thisq.parent: thisa = [a for a in thisq.parent.answers if a.to.index == thisq.index][0] chain.append((thisq.parent, thisa)) thisq = thisq.parent chain.reverse() fp = open("html/%s.html" % q.index, "w") fp.write(str(template(parent=q.parent, question=q, answers=answers, answer_to=answer_to, chain=chain))) fp.close()