【问题标题】:Python Trivia Game and reading from filesPython Trivia 游戏和读取文件
【发布时间】:2013-11-13 01:19:03
【问题描述】:
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|选择 2|选择 3|选择 4|答案|描述|点值 然后使用行。拆分('|')

标签: python oop


【解决方案1】:

分号分隔,即

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多