python - 存储最新 3 个分数 - SyntaxError : unexpected EOF while parsing

标签 python python-3.x

我正在使用 Python 3.x 创建一个程序,其中包含随机生成的简单算术问题(例如 3 x 8)的测验。测验将由 3 个不同类(class)的学校学生(不是真实的学生!)进行,并且应存储每个学生的最新 3 个分数。每个类(class)的分数应单独保存(在 3 个文本文件中)。

学生完成测验后,学生该次尝试的分数应添加到他们的分数中。

我创建了以下代码,其中filename是存储学生类(class)分数的文本文件的名称,score是学生刚刚获得的分数, fullName 是学生的全名(他们在开始时输入的),scores 是存储用户类(class)分数的字典:

with open(filename, "a+") as file:
    scores = ast.literal_eval(file.read())
#loads student's class' scores into dict

if fullName not in scores:
    scores[fullName] = collections.deque(maxlen=3)
#adds key for student if they haven't played before

scores[fullName].append(score)
#adds student's new score to their scores

with open(filename, "w") as file:
    file.write(str(scores))
#writes updated class scores to student's class' file

但是当我运行它时,我收到一个错误:

Traceback (most recent call last):
  File "E:\My Documents\Quiz.py", line 175, in <module>
    menu()
  File "E:\My Documents\Quiz.py", line 142, in menu
    scores = ast.literal_eval(file.read())
  File "C:\Python34\lib\ast.py", line 46, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "C:\Python34\lib\ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 0

    ^
SyntaxError: unexpected EOF while parsing

我认为这是因为文本文件是空的,所以当程序尝试读取它们时,它产生了错误。所以,我把它改成这样:

with open(filename, "a+") as file:
    try:
        scores = ast.literal_eval(file.read())
    except SyntaxError:
        scores = {}
#loads student's class' scores into dict, but if
#text file is empty, it creates empty dict by itself.

if fullName not in scores:
    scores[fullName] = collections.deque(maxlen=3)
#adds key for student if they haven't played before

scores[fullName].append(score)
#adds student's new score to their scores

with open(filename, "w") as file:
    file.write(str(scores))
#writes updated class scores to student's class' file

但是当我多次运行该程序时,无论是使用不同的名称还是使用相同的名称,都只会显示最新尝试的分数。我尝试将数据存储在文本文件中,然后在没有 try... except 语句的情况下运行程序,但仍然出现相同的 SyntaxError 。为什么会发生这种情况?请注意,我是初学者,所以我可能不明白很多事情。

最佳答案

您可以使用dequepickle,但为了简单起见,我们将使用 json使用列表转储字典来保存值:

# Unless first run for class we should be able to load the dict.

    try:
        with open(filename, "r") as f:
            scores = json.load(f)
    except FileNotFoundError:
        scores = {}

# game logic where you get score...

# try get users list of scores or create new list if it is their first go.
student_list = scores.get(fullName, [])

# if the user has three score remove the oldest and add the new.
# student_list[1:]  takes all but the first/oldest score.
if len(student_list) == 3:
     scores[fullName] = student_list[1:]  + [score]
else:
     # else < 3 so just append the new score.
     student_list.append(score)
     scores[fullName] = student_list


# dump dict to file.
with open(filename, "w") as f:
    json.dump(scores, f)

关于python - 存储最新 3 个分数 - SyntaxError : unexpected EOF while parsing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36680047/

相关文章:

python - 什么是迭代器、可迭代和迭代?

python - 根据变量字段进行分组,然后重置python中的计数器(cumcount)

Python 3.5 While 循环不进入 If 语句

python - 处理多个 KeyError 异常的更优雅的方式

python - 什么是 Python 中的简单英语处理程序

python构造函数默认参数列表

Python - 使用正则表达式编写模仿 strip() 方法的函数

python - 需要从curl迁移到pycurl的帮助

python - 三次样条插值得到系数

python-3.x - Selenium - 文本属性仅在调试器检查后才可用