如何让python测验随机化问题?

问题描述 投票:1回答:1

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

我尝试过使用import random,但语法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()  

这是与该计划相关的大部分代码。我将非常感谢任何可用的支持。

python python-3.x random
1个回答
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

等等。

© www.soinside.com 2019 - 2024. All rights reserved.