【问题标题】:How do I get a python quiz to randomize questions?如何获得 python 测验以随机化问题?
【发布时间】:2019-04-30 12:21:59
【问题描述】:

我的任务是使用 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】:

您可以读取文件并将其内容分成八个块。要生成唯一的随机问题,您可以使用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

等等

【讨论】:

    猜你喜欢
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多