尝试以标准的结构化格式(例如 JSON)存储您的数据。用于解析 JSON 的库包含在 Python中。
创建一个名为的文件,questions.json
其中包含:
{
“你今天有什么计划?”: {
“答案”:[“什么”,“某事”,“不知道”],
“正确答案”:2
},
“你好吗?”: {
“答案”:[“好”、“不好”、“不知道”]、
“正确答案”:1
}
}
然后你可以解析它并向用户询问一个随机问题,如下所示:
import json
import random
# read data from JSON file
questions = json.load(open("questions.json"))
# pick a random question
question = random.choice(questions.keys())
# get the list of possible answers and correct answer for this question
answers = questions[question]['answers']
correct_answer = questions[question]['correct_answer']
# display question and list of possible answers
print question
for n, answer in enumerate(answers):
print "%d) %s" % (n + 1, answer)
# ask user for answer and check if it's the correct answer for this question
resp = raw_input('answer: ')
if resp == str(correct_answer):
print "correct!"
else:
print "sorry, the correct answer was %s" % correct_answer
示例输出:
你今天有什么计划?
1) 没有
2) 某事
3)不知道
答案:3
抱歉,正确答案是 2