Python Trivia游戏和从文件中读取

时间:2013-11-01 19:00:02

标签: python oop

class Question(object):
def __init__(self, question, options, answer, description, points):
    self.question = question
    self.options = options
    self.answer = answer
    self.description = description
    self.points = points

def ask():
    response = None
    while response not in ("1", "2", "3", "4"):
        response = raw_input(self.question).lower()

    if response == self.answer:
        print "right"

    else:
        print "wrong"

问题=? 回答=?

我希望它能够解决我的问题,但我想从文本文件中添加问题和其他值。

这就是我到目前为止所做的,但我对如何从同一文本文件中添加问题,答案,类别和点值感到困惑。

文本文件示例trivia.txt:

Category
Question
Choice 1
Choice 2
Choice 3
Choice 4
Answer (being a digit 1-4)
Description why it is that answer
Point Value

1 个答案:

答案 0 :(得分:0)

半冒号分隔即

Category:Question:Choice 1:Choice 2:Choice 3:Choice 4:etc

读取它们并将它们传递给您的对象:

with open('questions.txt', 'r') as testfile:
    for line in testfile:
        question = (line.split(':'))

您知道有一个可迭代列表,可用于为问题指定值。这只是一种可能的解决方案。

您还可以查看词典路线:

Creating a dictionary from a string