#!/usr/bin/env python import re import sys def process_answer(match): global question,subquestion,args num = "%d%c" % (question,chr(ord('@')+subquestion)) if args.has_key('noanswers'): return '' if args.has_key('answers'): display = 'display:block' spacer = '

' prefix = '' else: display = 'display:none' spacer = '' prefix = """

""" % (num,num,num) return prefix+'
%s%s
' % (num,display,spacer,match.group(1)) def process_subquestion(match): global question,subquestion subquestion += 1 num = "%d%c" % (question,chr(ord('@')+subquestion)) prefix = """
  1. """ % (num,subquestion) suffix = '
' return prefix + re.sub(r'(?s)(.*?)',process_answer,match.group(1)) + suffix def process_question(match): global question,subquestion question += 1 subquestion = 0 prefix = """


Problem %d. """ % (question,question) suffix = '

' return prefix + re.sub(r'(?s)(.*?)',process_subquestion,match.group(1)) + suffix def process_questions(match): global question,args question = 0 if not args.has_key('answers') and not args.has_key('noanswers'): head = '' noscript = """ """ buttons = """   """ else: head = '' noscript = '' buttons = '' return (''+head+''+noscript+ '

'+match.group(1)+'

'+buttons+ re.sub(r'(?s)(.*?)',process_question,match.group(2))+ '') def process_file(contents,answers=0,noanswers=0): global args args = {} if answers: args['answers'] = 1 if noanswers: args['noanswers'] = 1 return re.sub(r'(?s)(.*)',process_questions,contents) if __name__ == '__main__': file = sys.argv[1] try: f = open(file+".xml") contents = f.read() f.close() except Exception,e: print 'Oops! Error while reading ',file,': ',e sys.exit() try: f = open(file+".html","w") f.write(process_file(contents)) f.close() f = open(file+"_answers.html","w") f.write(process_file(contents,answers=1)) f.close() f = open(file+"_noanswers.html","w") f.write(process_file(contents,noanswers=1)) f.close() except Exception,e: print 'Oops! Error while processing ',file,': ',e sys.exit()