def load_questions(file_path):
questions = []
with open(file_path, 'r', encoding='utf-8') as file:
reader = csv.reader(file)
next(reader) # 跳过表头
for row in reader:
question = {
'topic': row[0],
'content': row[1],
'options': row[2:6],
'answer': row[6]
}
questions.append(question)
return questions 从题目文件中加载题目列表,使用csv模块读取CSV文件,并将每一行的数据转化为题目字典。题目字典包括题目的标题、内容、选项和答案,并将所有题目字典存储在一个列表中。
load_questions函数接受一个文件路径作为参数,并返回一个题目列表。
open函数打开文件,并使用csv.reader函数将文件转换为一个可迭代的Reader对象。
next(reader)跳过表头,即读取文件中的第一行数据,通常是标题行。
reader对象,对于每一行数据,将题目的各个字段存储在一个字典中,并将该字典添加到题目列表中。
对于每一行数据,通过索引方法row[x]来获取相应的字段,将这些字段存储在一个字典中,然后将字典添加到题目列表中。
在这里,CSV文件的结构如下:
通过使用CSV模块的reader函数,我们可以方便地处理CSV文件,并将每一行数据转换为一个列表。然后可以使用列表的索引来获取特定的字段值。在这种情况下,题目的内容、选项和答案分别位于索引1到6的位置,因此可以通过切片操作将这些字段提取出来。最后,将提取出的字段分别存储在一个字典中,并将该字典添加到题目列表中。
display_question)def display_question(question_number, question):
print(f'题目{question_number}: {question["content"]}')
for i, option in enumerate(question['options']):
print('{}: {}'.format(chr(ord('A') + i), option)) 显示题目的内容,包括题目标题、选项和题号。通过循环遍历选项列表,并使用enumerate函数来获取选项的索引和选项内容,按照题号和选项的格式进行打印。
question_number和题目信息字典question作为参数。
print函数打印题目编号和题目内容,格式为题目{question_number}: {question["content"]}。
enumerate函数遍历题目的选项列表question['options']。enumerate函数返回一个迭代器,该迭代器会在每次迭代时返回一个包含索引和元素的元组。
chr(ord('A') + i)来生成选项的字母标识,ord('A')表示字母'A'的ASCII码,ord('A') + i表示字母依次递增。
print函数打印选项的字母标识和选项内容,格式为字母标识: 选项内容。

def check_answer(question, user_answer):
correct_answer = question['answer']
return user_answer.upper() == correct_answer.upper()判断用户的答案是否正确,并给与相应的反馈。
question和用户答案user_answer作为参数。
question中获取正确答案correct_answer。
user_answer.upper()和correct_answer.upper()将用户答案和正确答案转换为大写字母。
user_answer.upper()和正确答案correct_answer.upper()是否相等。
def main():
file_path = '单选题.csv'
questions = load_questions(file_path)
print('欢迎使用毛概刷题程序!')
print('请阅读题目并输入你的答案(A、B、C或D)')
correct_answers = 0
for i, question in enumerate(questions, 1):
display_question(i, question)
user_answer = input('请输入你的答案: ')
if check_answer(question, user_answer):
print('回答正确!')
correct_answers += 1
else:
correct_answer = question['answer']
print(f'回答错误!正确答案是: {correct_answer}')
file_path = '单选_1.csv'
with open(file_path, 'a', encoding='utf-8', newline='') as file:
writer = csv.writer(file)
writer.writerow([question['topic'], question['content'], question['options'][1], question['options'][0],
question['options'][2], question['options'][3], question['answer']])
print(f'你答对了 {correct_answers} 道题目。')先加载题目并打印欢迎信息,之后循环显示题目、接受用户答案、判断答案、给出反馈……
file_path,指定了题目文件的位置。
load_questions函数从指定的文件路径中加载题目信息,将加载的题目存储在questions列表中。
print函数打印欢迎信息和提示用户输入答案的说明。
correct_answers,用于记录用户回答正确的题目数量,初始值为0。
enumerate函数遍历题目列表questions,同时获取题目的索引i和题目信息字典question。
display_question函数打印题目和选项。
input函数等待用户输入答案,并将用户输入的答案存储在变量user_answer中。
check_answer函数检查用户的答案是否正确。
print函数打印回答正确的提示信息,并将correct_answers加1。
print函数打印回答错误的提示信息,以及正确答案。
单选_1.csv的文件中,以便后续参考。
print函数打印用户答对的题目数量。