如何用Python结合SQL填充试题模板并解决isCorrect字段失效问题
如何用Python结合SQL实现试题模板填充并修复正确选项显示问题
问题背景
需要用MSSQL查询返回的试题数据填充指定模板,生成符合格式的文本文件,但目前无法正确识别isCorrect字段来显示正确选项。
模板格式
Question: {QuestionStem} {answers} Correct answer: {correctAnswer} Date: {examDate} Class: {examClass}
原始SQL数据
| QuestionID | QuestionStem | QuestionOrder | AnswerId | AnswerText | AnswerOrder | isCorrect | Class | Date |
|---|---|---|---|---|---|---|---|---|
| 100 | What color is the sky? | 0 | 1 | Red | 0 | 0 | Astronomy | 10/1/2024 |
| 100 | What color is the sky? | 0 | 2 | Blue | 1 | 1 | Astronomy | 10/1/2024 |
| 100 | What color is the sky? | 0 | 3 | Orange | 2 | 0 | Astronomy | 10/1/2024 |
| 100 | What color is the sky? | 0 | 4 | Green | 3 | 0 | Astronomy | 10/1/2024 |
| 200 | The Sun is bright(T/F) | 1 | 11 | True | 0 | 1 | Astronomy | 5/1/2024 |
| 200 | The Sun is bright(T/F) | 1 | 12 | False | 1 | 0 | Astronomy | 5/1/2024 |
期望输出
Question: What color is the sky? a. Red b. Blue c. Orange d. Green Correct answer: b Date: 10/1/2024 Class: Astronomy Question: The Sun is bright(T/F) a. True b. False Correct answer: a Date: 5/1/2024 Class: Astronomy
当前问题
生成的文本中正确答案为空,选项格式也不符合要求:
Question: What color is the sky? -[ ] Red -[ ] Green -[ ] Gold -[ ] Blue Correct answer: Date: 2023-08-23 Class: Astro 101
解决方案
1. 核心思路
- 按
QuestionID分组处理数据,每个分组对应一道完整试题 - 根据
AnswerOrder生成a.、b.、c.这类选项标识 - 在分组内找到
isCorrect=1的选项,匹配其对应的字母标识作为正确答案 - 逐题填充模板后拼接所有内容,写入文件
2. 完整Python代码示例
使用pyodbc连接MSSQL,处理数据并生成目标文件:
import pyodbc from collections import defaultdict # 1. 连接MSSQL数据库 conn_str = ( r'DRIVER={ODBC Driver 17 for SQL Server};' r'SERVER=你的服务器地址;' r'DATABASE=你的数据库名;' r'UID=用户名;' r'PWD=密码;' ) conn = pyodbc.connect(conn_str) cursor = conn.cursor() # 2. 查询试题数据(按QuestionID和AnswerOrder排序,保证选项顺序正确) query = """ SELECT QuestionID, QuestionStem, AnswerText, AnswerOrder, isCorrect, Class, Date FROM 你的试题表名 ORDER BY QuestionID, AnswerOrder """ cursor.execute(query) rows = cursor.fetchall() # 3. 按QuestionID分组整理数据 questions = defaultdict(lambda: { 'stem': '', 'answers': [], 'correct': '', 'class': '', 'date': '' }) for row in rows: qid, stem, ans_text, ans_order, is_correct, cls, date = row # 生成选项字母(a对应0,b对应1...) ans_letter = chr(ord('a') + ans_order) ans_line = f"{ans_letter}. {ans_text}" questions[qid]['answers'].append(ans_line) questions[qid]['stem'] = stem questions[qid]['class'] = cls # 格式化日期为目标格式 questions[qid]['date'] = date.strftime('%m/%d/%Y') if hasattr(date, 'strftime') else str(date) # 记录正确选项的字母 if is_correct == 1: questions[qid]['correct'] = ans_letter # 4. 定义模板并填充内容 template = """Question: {stem} {answers} Correct answer: {correct} Date: {date} Class: {cls} """ output_content = [] for q_data in questions.values(): # 把答案列表转成换行分隔的字符串 ans_str = '\n'.join(q_data['answers']) # 填充模板 question_text = template.format( stem=q_data['stem'], answers=ans_str, correct=q_data['correct'], date=q_data['date'], cls=q_data['class'] ) output_content.append(question_text) # 5. 写入文本文件 with open('试题汇总.txt', 'w', encoding='utf-8') as f: f.write('\n\n'.join(output_content)) # 关闭数据库连接 cursor.close() conn.close()
3. 关键修复点
- 数据分组:用
defaultdict按QuestionID聚合同一题的所有选项,避免处理零散数据 - 正确选项匹配:遍历每一行时,若
isCorrect=1,直接记录该选项对应的字母标识,确保正确答案不会丢失 - 选项格式统一:根据
AnswerOrder生成标准的字母选项格式,替代原有不规范的-[ ]格式 - 日期格式化:将数据库返回的日期对象转成目标格式(如
10/1/2024)
内容的提问来源于stack exchange,提问作者SkyeBoniwell
相关产品推荐
相关产品推荐

