[英]Formatting issue from reading in text from text file in 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 -
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)
你不能拒絕的情節
媽媽奔跑
如果等待太久,會發生什么?
你最終會陷入困境
你最終會牛
你最終會遇到山羊
您將進入the
羔羊只是小羊。
五
教父現在會和你在一起
假設您有靈魂教父的觀眾。 / smart怎么樣
向他講話?
理查德先生
多米諾先生
布朗先生
方格先生
10
詹姆斯·布朗(James Brown)是靈魂的教父。
那將要花費你
如果您以盧比支付了暴民保護資金,那么您最會從事什么業務
可能會保險?
您在荷蘭的郁金香農場
您在印度的咖喱粉工廠
您的伏特加酒廠用俄語
您在瑞士的軍刀倉庫
盧比是印度的標准貨幣單位。
15
保持家庭
如果您母親的父親的姐姐的兒子在“家庭”中,您與暴徒有什么關系?
由您的第一個表親移除
由您的表弟兩次刪除
由你的第二個表親移除
被你的第二個堂兄兩次刪除
您母親的父親的姐姐是她的姑姑-兒子是您母親的第一個表親。 由於您和您的母親相差了一代人,她的第一個表親是您的第一個表親。
20
女仆
如果您要從字面上洗錢,但又不想讓鈔票上的綠色運行,那么應該使用什么溫度?
熱
暖
不溫不火
冷
根據我的洗滌劑瓶,對於可能出現的顏色而言,最好使用冷水。
25
我不確定您遇到了什么問題,因此我將向您提供一些有關代碼的一般注釋,希望更好的方法可以使您獲得更好的結果。
通常,在執行I / O時,請嘗試以盡可能靠近的方式打開和關閉文件,以免忘記關閉文件,從而使整個程序更易於調試。 如果您可以將with
語句用作上下文管理器, Python將為您提供真正的便利。
with open('filename.txt', 'r') as filename:
some_var = filename.read()
在該塊之后,文件some_var
自動為您關閉, some_var
的全部內容仍為字符串。
其次,雖然我認為以這種方式使用函數來抽象代碼的部分真的很酷 (這是一種值得的方法!),但我認為您應該抽象一些對問題集更為特定的東西。 例如,
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
,則可以在正常的try
/ except
塊中執行此操作,但是有時可以讓它冒泡。 畢竟,您的程序並沒有真正處理該異常,它只是報告該異常然后退出,如果您沒有捕獲到該異常,這正是發生的情況。 (另外,重新引發Exception或至少將錯誤消息打印到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]
等。 這比元組更自然地將事物組合在一起(這也要求您重復行category, question, answers, correct, explanation, point_val = next_block(trivia_file)
)。 注意,我也將答案分組到一個list
-這是答案列表! 您可以將每個這樣的dict
放在一個列表(字典列表)中,然后您便擁有了一整套瑣事問題。 您甚至可以通過在整個列表上使用random.shuffle
將順序隨機化!
嘗試重新組織文件,以便一次執行一件事。 讀取文件,從文件中獲取所需內容,然后完成操作 。 不要將讀取操作擴展到整個腳本。 解析問題,將其存儲在有用的地方(提示:您是否考慮過將它作為一個類?),然后再完成 。 然后遍歷已經結構化的問題並提出。 這將使您的程序更易於調試,生活也更輕松。 甚至可能對您現在擁有的東西有所幫助。 :)
"""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()
我實際上是在想您可能會以這種方式閱讀它。 當然,有很多更好的方法可以遍歷Python中的文件,但是對您來說,每一行都沒有意義,每行都是有意義的,因此可以說這很清楚。 (此外,您還必須處理這種糟糕的行繼續語法;如果不存在這種情況,則更好;但我認為您沒有建立文件格式。)
只需讀入文件,解析其內容,然后繼續。 現在它已在內存中,並且將在后台關閉。 您已經准備好玩瑣事。 我之前描述的所有字典現在都歸為一個很長的列表,因此您可以將它們隨機化:
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...
這將詢問每個問題一次。 一旦您到達列表的末尾,就沒有問題了,現在該游戲結束了!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.