在Python中从文本文件读取文本时的格式问题?

在Python中从文本文件读取文本时的格式问题?,python,Python,因此,我的任务之一是修改现有的琐事游戏,使每个问题都有一定的分值。游戏从一个文本文件中获取几乎所有的文本 但是,我有一些问题:出于某种原因,当我向文本文件添加一个点值时,它会弄乱程序的格式,并且不会打印一些行 当我运行它时,我得到以下信息: Welcome to Trivia Challenge! An Episode You Can't Refuse On the Run With a Mamma You'll end up on the goat 1 -

因此,我的任务之一是修改现有的琐事游戏,使每个问题都有一定的分值。游戏从一个文本文件中获取几乎所有的文本

但是,我有一些问题:出于某种原因,当我向文本文件添加一个点值时,它会弄乱程序的格式,并且不会打印一些行

当我运行它时,我得到以下信息:

    Welcome to Trivia Challenge!

    An Episode You Can't Refuse

  On the Run With a Mamma

  You'll end up on the goat

  1 - 

  2 - If you wait too long, what will happen?

  3 - You'll end up on the sheep

  4 - 

What's your answer?: 
我不知道怎么修。有什么帮助吗

这是程序文件和文本文件

# Trivia Challenge
# Trivia game that reads a plain text file

import sys

def open_file(file_name, mode):
    """Open a file."""
    try:
        the_file = open(file_name, mode)
    except(IOError), e:
        print "Unable to open the file", file_name, "Ending program.\n", e
        raw_input("\n\nPress the enter key to exit.")
    sys.exit()
    else:
        return the_file

def next_line(the_file):
    """Return next line from the trivia file, formatted."""
    line = the_file.readline()
    line = line.replace("/", "\n")
    return line

def next_block(the_file):
    """Return the next block of data from the trivia file."""
       category = next_line(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]

       explanation = next_line(the_file)

       point_val = next_line(the_file)

       return category, question, answers, correct, explanation, point_val

def welcome(title):
    """Welcome the player and get his/her name."""
    print "\t\tWelcome to Trivia Challenge!\n"
    print "\t\t", title, "\n"

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


  # get first block
    category, question, answers, correct, explanation, point_val = next_block(trivia_file)

    while category:
        # ask a question
        print category
        print question
        for i in range(4):
            print "\t", i + 1, "-", answers[i]

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

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

        # get next block
        category, question, answers, correct, explanation, point_val = next_block(trivia_file)

    trivia_file.close()

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

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

文本文件(trivia2.txt)

你无法拒绝的插曲

和妈妈一起跑

如果你等得太久,会发生什么

你最终会被羊吃掉的

你最终会死在牛身上

你会被抓的

你最终会上emu的

羔羊只是一只小绵羊

五,

教父现在会对你下手的

假设你有一个灵魂教父的听众。它会是怎样的/聪明的

向他讲话

理查德先生

多米诺先生

布朗先生

查克先生

十,

詹姆斯·布朗是灵魂的教父

那会让你付出代价的

如果你用卢比支付暴徒保护费,你最喜欢做什么生意

你可能在投保吗

荷兰的郁金香农场

你们在印度的咖喱粉工厂

你的俄罗斯伏特加酒厂

你在瑞士的军刀仓库

卢比是印度的标准货币单位

十五

把它留给家人

如果你母亲的父亲的姐姐的儿子在“家庭”里,你和暴徒有什么关系

被你的表亲带走了吗

两次被你的表亲带走

被你的第二个表弟带走了

被你的第二个表弟两次搬走

你母亲的父亲的妹妹是她的姑姑,她的儿子是你母亲的表亲。因为你和你母亲是一代人,她的表亲是你的表亲

二十

女仆

如果你真的要洗你的钱,但又不想让你的钞票上的绿色变亮,你应该用什么温度

热的

温暖的

温热的

冷的

根据我的洗涤剂瓶,冷是最好的颜色,可能会影响 跑

二十五


我不完全确定您遇到了什么问题,所以我将对您的代码提供一些一般性的评论,希望更好的方法能够带来更好的结果

一般来说,在执行I/O时,尽量靠近文件打开和关闭文件,这样您就不会忘记关闭它,从而使整个程序更易于调试。如果您可以将
with
语句用作上下文管理器,Python会使这一点变得非常简单

with open('filename.txt', 'r') as filename:
    some_var = filename.read()
在此块之后,filename将自动为您关闭,并且
某些变量仍然将其全部内容作为字符串

第二,虽然我认为以这种方式使用函数来抽象代码(这是一种值得的方法!)真的很酷,但我认为你应该抽象一些更具体的问题集。比如说,

def open_file(file_name, mode):
    """Open a file."""
    try:
        the_file = open(file_name, mode)
    except(IOError), e:
        print "Unable to open the file", file_name, "Ending program.\n", e
        raw_input("\n\nPress the enter key to exit.")
        sys.exit()
    else:
        return the_file
您的此函数将文件名作为参数和模式参数,尝试打开文件,并在无法打开文件时处理
IOError
。听起来很像内置的
open
,不是吗?那就用它吧!如果您需要处理
IOError
,您可以在正常的
中尝试处理
/
,但
块除外,但有时也可以让它冒泡。毕竟,你的程序并不是真的在处理异常,它只是在报告异常然后退出,如果你没有捕捉到它,这正是会发生的事情。(此外,重新引发异常或至少将错误消息打印到
sys.stderr
,这是另一种情况。)

我想告诉大家的最后一件事是关于数据结构的。当我看到您的数据块时,我看到的是:

{
    'category': line1,
    'question': line2,
    'answers': [line3, line4, line5, line6],
    'correct_answer': line7,
    'points': int(line7.strip()),
}
每个块都是一个
dict
,为一个问题对一组数据进行分组。如果将其存储为
q
,则可以调用
q['category']
q[answers][0]
,等等。这将以比元组更自然的方式将事物分组(这也要求您重复行
类别、问题、答案、更正、解释、点\u val=next\u块(琐事\u文件)
)。注意,我还将答案分组到一个
列表中
——这是一个答案列表!你可以把每一个这样的
dict
放到一个列表中(一个dict列表),然后你就有了一整套琐碎的问题。您甚至可以使用整个列表上的
random.shuffle
随机排列顺序

尝试重新组织文件,以便一次只做一件事。阅读文件,从中得到你想要的,然后处理它。不要在整个脚本上拉伸读取操作。解析出问题,把它们存储在有用的地方(提示:你有没有想过把它变成一个类?)。然后循环回答已经组织好的问题并提问。这将使您的程序更容易调试,您的生活也更轻松。甚至可能对您现在拥有的东西有所帮助。:)


快速示例 我在想你可能会读到这样的东西。在Python中迭代文件当然有更好的方法,但对您来说,每一行都没有意义,每几行都有意义,所以这可以说更清楚。(您还必须处理糟糕的行继续语法;如果没有更好,但我认为您没有建立文件格式。)

只需读入文件,解析其内容,然后移动
"""Trivia challenge example"""

from __future__ import print_function, with_statement

import sys


questions = []
with open('trivia_file.txt', 'r') as trivia_file:
    title = trivia_file.readline()
    line = trivia_file.readline()
    while line:
        q = {}
        q['category'] = line
        q['question'] = trivia_file.readline()
        if q['question'].endswith('/'):
            q['question'] = q['question'][:-1] + trivia_file.readline()
        q['answers'] = [trivia_file.readline() for i in range(4)]
        q['correct'] = trivia_file.readline()
        q['explanation'] = trivia_file.readline()
        q['points'] = int(trivia_file.readline())
        questions.append(q)
        line = trivia_file.readline()
import random
# if the questions are supposed to stay in order skip this step
random.shuffle(questions)
for question in questions:
    print('Next category: ', question['category'])
    print('Q: ', question['question'])
    print('The possible answers are:')
    for i in range(4):
        print('{}. {}'.format(i+1, question['answers'][i]))
    # etc...