好的,我们来详细解答这个问题。
以下是一个完整的示例代码,展示了如何实现上述功能:
import random
# 读取文本文件
def read_questions(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
return lines
# 解析数据
def parse_data(lines):
questions = []
current_question = {}
for line in lines:
line = line.strip()
if line.startswith("Question:"):
if current_question:
questions.append(current_question)
current_question = {"question": line[9:], "options": []}
elif line.startswith("Answer:"):
current_question["options"].append(line[7:])
if current_question:
questions.append(current_question)
return questions
# 随机排序
def shuffle_questions(questions):
random.shuffle(questions)
for question in questions:
random.shuffle(question["options"])
return questions
# 显示测验
def display_quiz(questions):
for idx, question in enumerate(questions):
print(f"\nQuestion {idx + 1}: {question['question']}")
for option in question["options"]:
print(f" - {option}")
# 主函数
def main():
file_path = "questions.txt"
lines = read_questions(file_path)
questions = parse_data(lines)
shuffled_questions = shuffle_questions(questions)
display_quiz(shuffled_questions)
if __name__ == "__main__":
main()
questions.txt
)Question: What is the capital of France?
Answer: Berlin
Answer: Madrid
Answer: Paris
Answer: Rome
Question: Which language is primarily spoken in Brazil?
Answer: Spanish
Answer: French
Answer: Portuguese
Answer: English
random.shuffle
函数通常是均匀的,但如果需要更复杂的随机算法,可以考虑使用numpy
库。通过上述步骤和代码示例,你可以实现一个简单的多项选择测验系统,并且能够处理常见的错误情况。
领取专属 10元无门槛券
手把手带您无忧上云