【问题标题】:Python 2.6 Trivia game, multiple choice and true/false at randomPython 2.6 琐事游戏,多项选择和随机真/假
【发布时间】:2014-03-27 21:50:27
【问题描述】:
import random
players = 0
player1 = 0
player2 = 0

def open_file(file_name, mode):
    try:
        the_file = open(file_name, mode)
    except(IOError), e:
        print 'Cannot open file', file_name + '. Try moving its location.'
        raw_input('\nPress enter to exit. ')
        sys.exit()
    else:
        return the_file

def next_line(the_file):
    line = the_file.readline()
    line = line.replace('/', '\n')
    return line

def main():    
    file = open_file('Trivia_Questions.txt', 'r')
    questions = file.read().split('\n\n')
    file.close()
    random.shuffle(questions)
    for question in questions.splitlines():
        if next_line(question) == 'Multiple Choice':
            subject, question, answer1, answer2, answer3, answer4, reason, empty  = map(question)
            print subject
            print question
            print '1 -', answer1
            print '1 -', answer1
            print '1 -', answer1
            print '1 -', answer1
            print reason
            subject, question, answer1, answer2, answer3, answer4, reason, empty = next_block(file)
        else:
            subject, question, answer1, answer2, reason, empty = map(question)
            print subject
            print question
            print '1 -', answer1
            print '2 -', answer2
            print reason
            print empty
            subject, question, answer1, answer2, reason, empty = next_block(file)



main()

我一直在寻找如何去做这件事,但不知道该怎么做。 当我尝试运行此代码时,我得到了

AttributeError: 'list' object has no attribute 'splitlines'

我的 txt 文件设置如下 多选 问题 答案1 答案2 答案3 答案4 正确答案# 原因

真/假 问题 吨 F 正确的 t 或 f 原因

重复 12 次​​p>

在我决定询问之前,我已经在网上搜索了 2 天,因此我们将不胜感激。我需要正确地让一个琐事游戏随机选择一个问题,无论是多选的真假,而不是再次使用该问题。

【问题讨论】:

  • 你可能会发现我的回答here很有用

标签: python python-2.6


【解决方案1】:

已经将文件拆分为一个列表:

questions = file.read().split('\n\n')

所以questions 是这里的列表。然后,您不能在此处尝试将 questions 拆分为新列表:

for question in questions.splitlines():

如果您想将每个单独的问题分成单独的行,请在循环中这样做:

for question in questions:
    for questionline in question.splitlines()

【讨论】:

  • 我做了你建议的改变,然后我得到一个错误,说地图需要 2 个参数。然后我更改了 next_line() 函数以将 '/' 值替换为 '\n',现在我得到 valueerror: too many subject to unpack
  • @user3407712:目前还不清楚你想在那里做什么; map() 可能不是您首先要寻找的功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多