用于绝对初学者的Python第7章挑战2

时间:2016-04-18 11:02:07

标签: python python-3.x python-3.4 python-3.3 python-3.5

我目前正在通过python进行绝对初学者第3次添加。我正在努力应对本书第7章中的第二次挑战,因为我一直得到一个我不理解的错误。

挑战在于:

“改进triva挑战游戏,以便在文件中保留高分列表。如果玩家列出了该列表,程序应该记录玩家的名字和分数。使用腌制对象存储高分。”

原始代码

# 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 as e:
        print("Unable to open the file", file_name, "Ending program.\n", e)
        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) 

    return category, question, answers, correct, explanation

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("trivia.txt", "r")
    title = next_line(trivia_file)
    welcome(title)
    score = 0

    # get first block
    category, question, answers, correct, explanation = 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 = input("What's your answer?: ")

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

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

    trivia_file.close()

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

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

我对挑战代码的尝试

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

import sys, pickle   

def open_file(file_name, mode):
    """Open a file."""
    try:
        the_file = open(file_name, mode)
    except IOError as e:
        print("Unable to open the file", file_name, "Ending program.\n", e)
        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)

    points = 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) 

    return category, points, question, answers, correct, explanation

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

def high_scores():
    global score
    value = int(score)
    name = input("What is your name? ")
    entry = (value, name)
    f = open("high_scores.dat", "wb+")
    high_scores = pickle.load(f)
    high_scores.append(entry)
    high_scores = high_scores[:5]
    print("High Scores\n")
    print("NAME\tSCORE")
    for entry in high_scores:
        value, name = entry
        print(name, "\t", value)
    pickle.dump(high_scores, f)
    f.close()

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

    # get first block
    category, points, question, answers, correct, explanation = 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 = input("What's your answer?: ")

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

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

    trivia_file.close()

    print("That was the last question!")
    print("You're final score is", score)
    high_scores()

score = 0

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

奇怪的混淆错误

Traceback (most recent call last):
  File "C:\Users\Cheyne\Desktop\Python\chapter07\Challenges\temp.py", line 104, in <module>
    main()
  File "C:\Users\Cheyne\Desktop\Python\chapter07\Challenges\temp.py", line 100, in main
    high_scores()
  File "C:\Users\Cheyne\Desktop\Python\chapter07\Challenges\temp.py", line 54, in high_scores
    high_scores = pickle.load(f)
  File "C:\Python31\lib\pickle.py", line 1365, in load
    encoding=encoding, errors=errors).load()
EOFError

有人可以帮忙解释这里出了什么问题吗?我已经盯着它好几天了。

1 个答案:

答案 0 :(得分:0)

你有一个&#34; EOFError&#34;,这是&#34;文件结束错误&#34;在第54行。

你尝试加载pickle文件的地方,所以考虑到你没有检查文件是否存在,我猜你没有文件并且得到了错误。

要么自己创建一个初始文件,要么在尝试加载之前检查它是否存在并且是否有效。

编辑:我刚刚注意到你打开pickle文件为&#34; wb +&#34;,这意味着你打开它进行写入并尝试阅读它。您正在覆盖该文件,该文件变为零字节。如果要附加到现有文件,则应使用&#34; a&#34;而不是&#34; w&#34;。再次,在加载之前确保文件包含有效数据。