microsoft/AI-For-Beginners
Publicmirrored fromhttps://github.com/microsoft/AI-For-BeginnersAvailable
etc/quiz-src/qzmkjson.py
62lines · modecode
| 1 | src = 'questions-en.txt' |
| 2 | dst_dir = '../quiz-app/src/assets/translations/en' |
| 3 | |
| 4 | import json,os |
| 5 | from copy import deepcopy |
| 6 | |
| 7 | from matplotlib.cbook import ls_mapper |
| 8 | |
| 9 | def mk_id(s): # convert from 4B/4E to numeric lesson id |
| 10 | lesson_no = int(s[:-1]) |
| 11 | return lesson_no + (100 if s[-1]=='B' else 200) |
| 12 | |
| 13 | with open('template.json') as f: |
| 14 | doc = json.load(f) |
| 15 | |
| 16 | inp = open(src,encoding='utf-8').readlines() |
| 17 | |
| 18 | prev_q = None |
| 19 | prev_l = None |
| 20 | prev_l_id = None |
| 21 | lessons = { } |
| 22 | |
| 23 | for l in inp: |
| 24 | l = l.strip() |
| 25 | if l=='': continue |
| 26 | if l.startswith('+') or l.startswith('-'): # answer |
| 27 | prev_q['answerOptions'].append({ "answerText" : l[2:], "isCorrect" : l.startswith('+') }) |
| 28 | elif l.startswith('*'): |
| 29 | if prev_q: |
| 30 | prev_l['quiz'].append(prev_q) |
| 31 | prev_q = { "questionText" : l[2:], "answerOptions" : [] }; |
| 32 | elif l.startswith('Lesson'): |
| 33 | if prev_q: |
| 34 | prev_l['quiz'].append(prev_q) |
| 35 | prev_q = None |
| 36 | if prev_l is not None: |
| 37 | lessons[prev_l_id] = prev_l |
| 38 | prev_l_id = l[7:l.find(' ',7)] |
| 39 | prev_l = { "id" : mk_id(prev_l_id), "title" : l[l.find(' ',7)+1:], "quiz" : [] } |
| 40 | else: |
| 41 | print(f"Error: {l}") |
| 42 | |
| 43 | prev_l['quiz'].append(prev_q) |
| 44 | lessons[prev_l_id] = prev_l |
| 45 | |
| 46 | lesson_content = {} |
| 47 | for k,v in lessons.items(): |
| 48 | no = int(k[:-1]) |
| 49 | if no not in lesson_content.keys(): |
| 50 | lesson_content[no] = deepcopy(doc) |
| 51 | lesson_content[no][0]['quizzes'].append(v) |
| 52 | |
| 53 | with open(os.path.join(dst_dir,'index.js'),'w',encoding='utf-8') as f: |
| 54 | for i,k in enumerate(lesson_content.keys()): |
| 55 | f.write(f'import x{k} from "./lesson-{k}.json";\n') |
| 56 | t = ', '.join([ f"{i} : x{k}[0]" for i,k in enumerate(lesson_content.keys())]); |
| 57 | f.write(f"const quiz = {{ {t} }}; \n"); |
| 58 | f.write("export default quiz;") |
| 59 | |
| 60 | for k,v in lesson_content.items(): |
| 61 | with open(os.path.join(dst_dir,f"lesson-{k}.json"),'w', encoding='utf-8') as f: |
| 62 | json.dump(v,f,indent=2) |
| 63 | |