随机测验生成器

时间:2016-11-21 03:48:24

标签: python dictionary matplotlib graphing

我的代码存在问题,我不知道如何随机抽取问题。这是代码,它一直给我一个关键错误。我试图从问题列表中打印一个随机问题,但它告诉我问题是一本字典。谁能帮我??

这是代码

#import matplotlib.pyplot as plt
import random, math, csv

def read_database(filename):
    dictionary = {}

    infile = open(filename, 'r')
    for line in infile:
        line = line.strip()
        q,a1,a2,a3,a4 = line.split(',')
        question = (q)
        answers = [a1,a2,a3,a4]
        dictionary[question] = answers
    infile.close()
    return dictionary

def read_results(outfile, score):
    player = {}
    outfile = open(outfile, "w")
    name = input("What is your name?")
    player[name] = score
    print(score, file = outfile)

    outfile.close()

def ask_question(question, answers):
    score = 0
    print(question[0])
    for multi in answers[1:5]:
        print(multi)
    answer = input("Please select an answer: ")
    print()
    if answer == answer[0]:
        print("Correct!")
        score += 1
    else:
        print("Incorrect! - the correct answer was {0}.".format(answer[0]))
    print()
    return score

def main():
    questions = read_database("data.csv")

    score = 0
    score = int(score)
    print()
    print()
    print("=============================")
    print("Welcome to the baseball quiz!")
    print("=============================")
    print()
    print()
    name = input("What is your name?")
    number = int(input("Hi," + name + " there are {0} questions - how many do you want in your quiz: ".format(len(questions))))
    if number > len(questions):
        print("The quiz only has 10 questions, you will be asked 10 questions. ")
    else:
        print("You will be asked", number, "quesitons")
    key_list = random.sample(questions.keys(), number)
    #print(key_list)
    score = 0
    for key in key_list:
        print(key, questions.get(key))
        score = ask_question(questions, key)
        print(score)

    print("Your final score was {0} out of {1}.".format(score,number), score/100)

if __name__ == "__main__":
    main()

这是我在csv文件中的数据样本:

  

谁赢得了今年的世界大赛?小熊队,大都会队,红雀队,印第安人队

     

有多少球员在场上进行防守?,九,六,十,二十

     

棒球比赛中有多少局?,九,十,七,六

1 个答案:

答案 0 :(得分:0)

函数ask_question(question, answers)需要将问题和可能答案列表作为参数。

因此你需要像这样调用它

score = ask_question( key, questions.get(key))

在这种情况下,key是问题,可能的答案列表为questions.get(key)