gpt4 book ai didi

python - 用户分数保存程序

转载 作者:太空宇宙 更新时间:2023-11-04 10:28:02 26 4
gpt4 key购买 nike

我正在尝试制作一个程序,它会询问用户的姓名,然后是一系列问题。每答对一题加分。我试图让它将分数和用户名一起存储到一个文本文件中,这样它在文本文件中看起来就像这样:

Name    Score 

所以让我们以约翰为例,如果他得了 4 分,在文本文件中它会写:

John    4

但我希望这样,如果约翰再次参加考试而不是让约翰参加两次考试:

John    4
John 6

我希望它显示为:

John    4   6

它不会重写姓名和乐谱,而是先将制表符和乐谱写到与名称为 John in 的行相同的行上。

到目前为止,这是我的代码:

import random
name = input("Hello user, what is your name?")
count = (0)
score = (0)
while count != (8):
count = count + (1)
symbols = ['+', '-', '*']
valueF = random.randint(1,10)
valueS = random.randint(1,10)
chosensymb = random.choice (symbols)
question = input("What is %d %s %d ? :"%(valueF, chosensymb, valueS))
answer = eval(str(valueF) + chosensymb + str(valueS))
if question == str(answer):
score = score + (1)
print ("Correct")
else:
print ("Incorrect")

print("%s, you have scored %d points"%(name,score))
filewrite = open("ScoreSheet.txt","a")
filewrite.write("\n%s\t%d"%(name,score))
filewrite.close()

我不知道该怎么做,我是 python 的新手,如果我有任何错误,请见谅,谢谢!

最佳答案

只是serialize您的数据使用 picklejson .这是一个使用 json 序列化分数的示例(将分数存储在 dict 中 - 名称和分数之间的映射):

# import the serializing library
import json as serializer

现在我们将创建一个函数来将乐谱写入给定文件:

def write_score(score_file_name, name, score):
scores = read_scores(score_file_name)
# add score
scores[name] = score
with open(score_file_name, 'w') as f:
serializer.dump(scores, f)

它的作用是:

  1. 从分数文件(dict)加载序列化结果对象
  2. 更新分数dict(添加key/更新key的值)
  3. 将更新后的 dict 写入文件(使用 json.dump )

在编写 write_score 函数时,我们缺少一个 read_scores 函数,它使我们能够查看当前分数。所以让我们写这个read_scores:

def read_scores(score_file_name):
try:
with open(score_file_name, 'r') as f:
scores = serializer.load(f)
return scores
except IOError:
# if file does not exist - we have no scores
return {}

read_scores 的作用是:

  1. 读取序列化的dict(使用json.load)

现在我们可以测试它是否真的有效。这是一个小例子:

# set the score file name
SCORES_FILE_NAME = 'scores.txt'

write_score(SCORES_FILE_NAME, 'john', 10)
print(read_scores(SCORES_FILE_NAME))

write_score(SCORES_FILE_NAME, 'jim', 11)
print(read_scores(SCORES_FILE_NAME))

# overwrite john's score
write_score(SCORES_FILE_NAME, 'john', 12)
print(read_scores(SCORES_FILE_NAME))

提示 1:您可能需要使用 name.lower()在编写乐谱时,johnJohn 被视为同一用户。

技巧2:因为我们引用了json库作为serializer,它和pickle有相同的API >,您只需将 import json as serializer 替换为 import pickle as serializer 即可在两者之间进行选择。 只需确保删除乐谱文件,因为它们不会以相同的方式序列化数据

整个代码在一起:

# import the serializing library
import json as serializer

def write_score(score_file_name, name, score):
scores = read_scores(score_file_name)
# add score
scores[name] = score
with open(score_file_name, 'w') as f:
serializer.dump(scores, f)


def read_scores(score_file_name):
try:
with open(score_file_name, 'r') as f:
scores = serializer.load(f)
return scores
except IOError:
# if file does not exist - we have no scores
return {}

# TESTS

# set the score file name
SCORES_FILE_NAME = 'scores.txt'

write_score(SCORES_FILE_NAME, 'john', 10)
print(read_scores(SCORES_FILE_NAME))

write_score(SCORES_FILE_NAME, 'jim', 11)
print(read_scores(SCORES_FILE_NAME))

# overwrite john's score
write_score(SCORES_FILE_NAME, 'john', 12)
print(read_scores(SCORES_FILE_NAME))

输出:

{u'john': 10}
{u'john': 10, u'jim': 11}
{u'jim': 11, u'john': 12}

要读取特定分数,您可以使用现有方法 read_scores:

def read_score(score_file_name, name):
return read_scores(score_file_name)[name]

奖金 - Closures :

如果您了解闭包,您可以通过以下方式使函数特定于文件:

def write_score(score_file_name):
# create closure specific to 'score_file_name'
def write_score_specific(name, score):
scores = read_scores(score_file_name)
# we're going to make a 'read_scores' with closures as well!
# so use that one...
scores_reader = read_scores(score_file_name)
scores = scores_reader()


# add score
scores[name] = score
with open(score_file_name, 'w') as f:
serializer.dump(scores, f)

# return file-specific function
return write_score_specific

现在,我们只需要调用带有文件名参数的函数一次,从那一刻起我们就可以使用结果来写入分数:

# create specific 'write_score' for our file
score_txt_writer = write_score('scores.txt')

# update john's score to 10 without specifying the file
score_txt_writer('john', 10)

read_score 也是如此:

def read_scores(score_file_name):
# create closure function
def read_scores_specific():
try:
with open(score_file_name, 'r') as f:
scores = serializer.load(f)
return scores
except IOError:
# if file does not exist - we have no scores
return {}
return read_scores_specific

包含闭包的完整代码:

# import the library
import serializer

# CLOSURES

SCORES_FILE = 'scores.txt'
def read_scores(score_file_name):
# create closure function
def read_scores_specific():
try:
with open(score_file_name, 'r') as f:
scores = serializer.load(f)
return scores
except IOError:
# if file does not exist - we have no scores
return {}
return read_scores_specific

def write_score(score_file_name):
# create closure specific to 'score_file_name'
def write_score_specific(name, score):
scores_reader = read_scores(score_file_name)
scores = scores_reader()
# add score
scores[name] = score
with open(score_file_name, 'w') as f:
serializer.dump(scores, f)

# return file-specific function
return write_score_specific

# create specific 'write_score' for our file
score_txt_writer = write_score(SCORES_FILE)

# update john's score to 10 without specifying the file
score_txt_writer('john', 10)


score_txt_reader = read_scores(SCORES_FILE)

print score_txt_reader()

输出:

{u'john': 10}

关于python - 用户分数保存程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28326725/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com