import random from vocab import get_words_from_source from sentences import get_sentence # 生成單字選擇題 def generate_fill_in_blank_exam(source, num): words_data = get_words_from_source(source) words = random.sample(words_data, num) questions = [] for word_data in words: word = word_data['word'] phonetic = word_data['phonetic'] # 取得例句 sentence_data = get_sentence(word) if not sentence_data: continue # 沒例句的跳過 sentence = sentence_data[2] blank_sentence = sentence.replace(word, '______') # 生成干擾選項 (亂數抽 3 個其他單字) other_words = [w['word'] for w in words_data if w['word'] != word] distractors = random.sample(other_words, 3) options = [word] + distractors random.shuffle(options) questions.append({ "sentence": blank_sentence, "options": options, "answer": word, "phonetic": phonetic }) # 將問題渲染為 HTML 以便 Gradio 顯示 if not questions: return "
❌ 無法生成試卷,可能單字缺少例句
" exam_html = "" for i, q in enumerate(questions): exam_html += f"第 {i + 1} 題: {q['sentence']}
" for option in q['options']: exam_html += f" {option} " exam_html += "得分: {score}
" for res in results: color = 'green' if res['is_correct'] else 'red' result_html += f"題目: {res['question']}
" \
f"你的答案: {res['user_answer']}
" \
f"正確答案: {res['correct_answer']}