Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我如何获得一个python测验来随机化问题?_Python_Python 3.x_Random - Fatal编程技术网

我如何获得一个python测验来随机化问题?

我如何获得一个python测验来随机化问题?,python,python-3.x,random,Python,Python 3.x,Random,我的任务是使用python进行测验,将问题存储在外部文件中。然而,我不知道如何让我的问题随机化,在20个可能的问题中一次只显示10个 我尝试过使用import random,但是语法random.shuffle(问题)似乎无效。我不知道现在该怎么办 question.txt文件的格式如下: 类别 问题: 答复 答复 答复 答复 正确答案 解释 我的代码: #allows program to know how file should be read def open_file(file_nam

我的任务是使用python进行测验,将问题存储在外部文件中。然而,我不知道如何让我的问题随机化,在20个可能的问题中一次只显示10个

我尝试过使用import random,但是语法
random.shuffle(问题)
似乎无效。我不知道现在该怎么办

question.txt文件的格式如下:

类别
问题:
答复
答复
答复
答复
正确答案
解释
我的代码:

#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()  

这是与程序相关的大部分代码。我将非常感谢您的支持。

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

您需要在文件的一个过程中阅读所有问题及其答案,然后可能将问题(及其答案)重新排列,最后依次提问。(另见:)