我正在尝试运行一个程序来管理基于文本文件内容的测验。我的代码如下所示:
HOW_MANY_QUESTIONS = 10
answers_file =开放( 'quiz_answers.txt', 'R')
results_file =开放( 'quiz_results.txt', 'W')
def main():
#dictionary with quiz answers
answer_dictionary={}
#run create dictionary function, result is the answer dictionary
answer_dictionary=create_dictionary(answers_file)
#close the files
answers_file.close()
results_file.close()
go_again='yes'
while go_again=='yes':
#get name
name=input('Enter your name: ')
#initialize count variable
count=0
#accumulator for number of correct answers
number_correct=0
for count in range(0,HOW_MANY_QUESTIONS+1):
#pick question function
answer=pick_question(answer_dictionary)
if answer:
number_correct+=1
results_file.write(name,number_correct)
go_again=input('Go again? ')
def create_dictionary(infile):
#establish a dictionary
dictionary={}
#initialize a key
key=0
#read the first line that is a state
state=infile.readline()
#strip the new line
state=state.rstrip('\n')
#while the line is not blank
while state!='':
#add it as the dictionary key
key=state
#read the capital line
capital=infile.readline()
#strip new line
capital=capital.rstrip('\n')
#read the govenror line
governor=infile.readline()
governor=governor.rstrip('\n')
#assign a list with capital and governor to the state key
dictionary[key]=[capital,governor]
return dictionary
def pick_question(字典):
#make a list containing the keys
keys=[]
#isolate the keys and append to the key list
for key in dictionary.keys():
keys.append(key)
#import random
import random
#initialize an index for keys list
key_index=0
#randomly select the state to ask about
state_selection=random.randint(0,len(keys)-1)
key_index=state_selection
#assign value to capital and governor to randomly
#select which question to ask
capital=1
governor=2
#randomly select whether to ask for the governor or the capital
question_choice=random.randint(capital,governor)
#if the question choice is for capital
if question_choice==capital:
#ask the capital question
question=input('What is the capital of',keys[key_index],'? ')
#if the answer is a value for that key
if question in keys[key_index]:
#it is correct
answer=True
#if the question choice is for governor
elif question_choice==governor:
#ask the governor question
question=input('Who is the governor of',keys[key_index],'?')
#if the answer is a value for that key
if question in keys[key_index]:
#it is correct
answer=True
return answer
main()的
当我运行程序时,我得到的错误是:
state = infile.readline()文件“/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py”,第26行,解码 return codecs.ascii_decode(input,self.errors)[0] UnicodeDecodeError:'ascii'编解码器无法解码位置36的字节0xff:序数不在范围内(128)
所以问题源于阅读文本文件的第一行;问题是什么?我该如何解决?我以前从未见过这个错误。提前谢谢!
答案 0 :(得分:0)
无论您打开infile,都需要使用正确的编码打开它。有关如何执行此操作的详细信息:
最有可能的问题是您使用的是Python 2.7并尝试打开utf-8文件。