从文件python中读取多项选择题和答案

时间:2014-11-13 23:00:21

标签: python file file-handling

大家好我试图设置一个从文件中读取问题和答案的测验,我是一个python初学者,我已经设置了代码,但我无法让它以正确的格式显示问题从文件,每行不是我想要的顺序,下面是我到目前为止的代码以及我的文本文件的布局

代码:

import sys

def open_file(file_name, mode):
    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):
    line = the_file.readline()
    line = line.replace("/", "\n")
    return line 

def next_block(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]

    return question, answers, correct

def welcome(title):
    print("\t\tWelcome to who wants to be a millionaire quiz\n")
    print("\t\t", title, "\n")

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

# get first block
    question, answers, correct = next_block(question_file)

    for i in range(3):
            print("\t", i + 1, answers[i])

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

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

        # get next block
        question, answers, correct = next_block(question_file)

        question_file.close()

        print("That was the last question!")
        print("You're final score is", score)

main()  
input("\n\nPress the enter key to exit.")

这是文本文件的布局: 完成詹姆斯邦德电影The Man With The Golden的称号。题 面对答案1 手回答2 眼睛回答3 枪回答4 2正确答案 两支球队在哪支运动中拉绳索的两端 网球 足球 曲棍球 拔河比赛 3

0 个答案:

没有答案