如何获得python测验以随机化问题?

时间:2019-04-30 12:21:59

标签: python python-3.x random

我的任务是使用python进行测验,并将问题存储在外部文件中。但是,我无法弄清楚如何让我的问题随机化,只能一次显示20个中的10个。

我尝试使用导入随机,但是语法random.shuffle(question)似乎无效。我不确定现在该怎么办。

question.txt 文件的布局为:

Category
Question
Answer
Answer
Answer
Answer
Correct Answer
Explanation 

我的代码:

#allows program to know how file should be read
def open_file(file_name, mode):
    """Open a file."""
    try:
        the_file = open(file_name, mode)
    except IOError as e:
        print("Unable to open the file", file_name, "Ending program.\n", e)
        input("\n\nPress the enter key to exit.")
        sys.exit()
    else:
        return the_file

def next_line(the_file):
    """Return next line from the trivia file, formatted."""
    line = the_file.readline()
    line = line.replace("/", "\n")
    return line

#defines block of data 
def next_block(the_file):
    """Return the next block of data from the trivia file."""
    category = next_line(the_file)
    question = next_line(the_file)

    answers = []
    for i in range(4):
        answers.append(next_line(the_file))

    correct = next_line(the_file)
    if correct:
        correct = correct[0]

    explanation = next_line(the_file)
    time.sleep(1.5)

#beginning of quiz questions

def main():
    trivia_file = open_file("trivia.txt", "r")
    title = next_line(trivia_file)
    welcome(title)
    score = 0

    # get first block
    category, question, answers, correct, explanation = next_block(trivia_file)
    while category:
        # ask a question
        print(category)
        print(question)
        for i in range(4):
            print("\t", i + 1, "-", answers[i])

        # get answer
        answer = input("What's your answer?: ")

        # check answer
        if answer == correct:
            print("\nCorrect!", end=" ")
            score += 1
        else:
            print("\nWrong.", end=" ")
        print(explanation)
        print("Score:", score, "\n\n")

        # get next block
        category, question, answers, correct, explanation = next_block(trivia_file)

    trivia_file.close()

    print("That was the last question!")
    print("Your final score is", score)


main()  

那是与程序相关的大多数代码。我将非常感谢您提供的任何支持。

1 个答案:

答案 0 :(得分:0)

您可以读取文件并将其内容分为八个块。要生成唯一的随机问题,可以使用random.shuffle,然后列出切片以创建问题组。另外,使用collections.namedtuple来构成问题的属性以供以后使用更干净:

import random, collections
data = [i.strip('\n') for i in open('filename.txt')]
questions = [data[i:i+8] for i in range(0, len(data), 8)]
random.shuffle(questions)
question = collections.namedtuple('question', ['category', 'question', 'answers', 'correct', 'explanation'])
final_questions = [question(*i[:2], i[2:6], *i[6:]) for i in questions]

现在,创建10的组:

group_questions = [final_questions[i:i+10] for i in range(0, len(final_questions), 10)]

结果将是包含namedtuple对象的列表的列表:

[[question(category='Category', question='Question', answers=['Answer', 'Answer', 'Answer', 'Answer'], correct='Correct Answer', explanation='Explanation ')]]

要从每个namedtuple中获得所需的值,可以查找属性:

category, question = question.category, question.question

等等。