Python 2.6 Trivia游戏,多项选择和随机的真/假

时间:2014-03-27 13:47:35

标签: python python-2.6

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文件设置如下 多选 题 ANSWER1 ANSWER2 ANSWER3 answer4 正确答案# reasonwhy

真/假 题 Ť F 纠正t或f reasonwhy

重复12次

我在网上搜索了2天才决定要求,所以我们非常感谢您的帮助。我需要正确地让一个琐事游戏随机选择一个问题,无论是多选的真/假,都不再使用这个问题。

1 个答案:

答案 0 :(得分:2)

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

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

所以questions是一个列表。然后,您无法尝试将questions拆分为新列表:

for question in questions.splitlines():

如果您想将每个个别问题分成不同的行,请在循环中执行此操作:

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