Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何创建字典并将数据保存到文本文件?(问答游戏python)_Python_List_Dictionary - Fatal编程技术网

如何创建字典并将数据保存到文本文件?(问答游戏python)

如何创建字典并将数据保存到文本文件?(问答游戏python),python,list,dictionary,Python,List,Dictionary,这是python,我使用的是空闲版本3.4.2。 因此,目前我的代码正常工作,但我希望对其进行调整,以便能够: 保存名称的最近三个分数(当他们重新运行代码并且分数保存在文本文件中时)。然而,有一个问题是,无论输入什么“名称”,它都会将分数重新保存在自己的行中,而不是“附加”(我知道这是因为它没有以列表/字典的形式保存,但我该怎么做?-或者我读到你可以“拆分”行?) 这是我的第一个问题,如果有人能帮助我,我将非常感激,我是python新手,所以这对我来说是一个ab ig挑战!欢迎提出任何意见或建议

这是python,我使用的是空闲版本3.4.2。 因此,目前我的代码正常工作,但我希望对其进行调整,以便能够: 保存名称的最近三个分数(当他们重新运行代码并且分数保存在文本文件中时)。然而,有一个问题是,无论输入什么“名称”,它都会将分数重新保存在自己的行中,而不是“附加”(我知道这是因为它没有以列表/字典的形式保存,但我该怎么做?-或者我读到你可以“拆分”行?)

这是我的第一个问题,如果有人能帮助我,我将非常感激,我是python新手,所以这对我来说是一个ab ig挑战!欢迎提出任何意见或建议

import random #import module
print("What is your name?") #prints writing in brackets
name = input().title() #Capitalizes the first letter of the word inputted
print("What class are you in? (Enter 1, 2 or 3)") #asks the user to input a number

while True:
   try:
       class_number = int(input()) #asks for an integer input from user
   except ValueError: 
       print("Sorry, I didn't understand that, please try again") #print statement
       continue

   if class_number > 3: #if input is more than 3
       print("SORRY but that class isn't recognised, try again") #print statement
       continue
   else:
       print ("Hello,", name, "from class", class_number, "welcome to my quiz") #prints writing in brackets and anything saved in the variable "name" and "class_number"
       break #break out of loop

score = 0  #sets the variable "score" to zero
question = 0 # sets the variable "question" to zero

while question < 3:#If questions (intitally set to 0) is smaller than 10, carry out this function
   question +=1 # add one to the value of "question"
   maths = random.randint(1,3) #randomly generate a number from 1-3 and store as "maths"
   num1 = random.randint(1,10)#randomly generate an integer from 1-10 and store as "num1"
   num2 = random.randint(1,10)#randomly generate a second integer from 1-10 and store as "num2"
   if maths == 1: #if the number generated is 1 
       print(num1, "+", num2) #prints num1 + num2
       ans = num1 + num2 #sets "ans" to equal the value of num1 added to num2

   elif maths == 2: #if the number generated is 1
       print(num1, "*", num2) #print num1 multiplied by num2
       ans = num1 * num2 #sets "ans" to equal the value of num1 multiplied by num2

   else: #else run this part of code
       print(num1, "-", num2) #print num1 subtracted by num2
       ans = num1 - num2 #sets "ans" to equal the value of num1 subtracted by num2

   while True:
       try:
           user_ans = int(input()) #user inputs answer to question
       except ValueError: #runs when the user input is no an integer
           print ("SORRY but that answer isn't recognised, try again")
       else:
           break

   if user_ans == ans:
       score+=1
       print("Well done, you are CORRECT")

   else:
       print("SORRY, you are INCORRECT") #print writing in brackets
       print("The correct answer was", ans)

if score == 10: #run this part of code if "score" equals 10
       print("fantastic", name, "you got full marks!") #print statement and name 
elif score >= 6: #run this part of code if "score" is larger than or equal to 6
       print("well done, there's some improvement to be done here though", name, "you got", score, "/10")# then print statement and score
elif score <=5: #run this part of code if "score" is smaller than or equal to 5
       print("hmm, maybe some more practise would be beneficial", name, "you got", score, "/10") #then print statement and score

class_number = str(class_number) + ".txt" #this adds '.txt' to the end of the file (therefore creating a text file) so it can be used to create a file under the name of the class
file = open(class_number, 'a') #opens the file in 'append' mode so you don't delete all the information
file.write(str(name + " : ")) #writes the name and ":" to file
file.write(str(score)) #writes the score to file
file.write('\n')#writes the score to the file
file.close()#safely closes the file to save the information

view = int(input("would you like to view the scores? If yes, press 1 or not press 2"))
if view == 1:
   exit
elif view == 2:
   exit #to be completed
导入随机#导入模块
打印(“你叫什么名字?”)#打印括号内的文字
name=input().title()大写输入单词的第一个字母
打印(“您在哪个班级?(输入1、2或3)”#要求用户输入一个数字
尽管如此:
尝试:
class_number=int(input())#要求用户输入整数
除值错误外:
打印(“对不起,我不明白,请再试一次”)#打印声明
持续
如果类别号>3:#如果输入大于3
打印(“抱歉,该类无法识别,请重试”)#打印语句
持续
其他:
打印(“你好”,姓名,“来自班级”,班级编号,“欢迎参加我的测验”)#打印括号中的文字以及变量“姓名”和“班级编号”中保存的任何内容
断开
score=0#将变量“score”设置为零
question=0#将变量“question”设置为零
当问题<3时:#如果问题(初始设置为0)小于10,则执行此功能
问题+=1#在“问题”的值上加一
数学=随机。randint(1,3)#从1-3中随机生成一个数字并存储为“数学”
num1=random.randint(1,10)#随机生成1-10之间的整数并存储为“num1”
num2=random.randint(1,10)#从1-10中随机生成第二个整数并存储为“num2”
如果数学==1:#如果生成的数字为1
打印(num1,“+”,num2)#打印num1+num2
ans=num1+num2#将“ans”设置为等于num1加在num2上的值
elif数学==2:#如果生成的数字为1
打印(num1,“*”,num2)#打印num1乘以num2
ans=num1*num2#将“ans”设置为等于num1乘以num2的值
else:#else运行这部分代码
打印(num1,“-”,num2)#打印num1减去num2
ans=num1-num2#将“ans”设置为等于num1的值减去num2
尽管如此:
尝试:
user_ans=int(input())#用户输入回答问题
ValueError除外:#在用户输入不是整数时运行
打印(“很抱歉,无法识别该答案,请重试”)
其他:
打破
如果用户_ans==ans:
分数+=1
打印(“做得好,你是对的”)
其他:
打印(“对不起,你错了”)#在括号中打印文字
打印(“正确答案是”,ans)
如果分数=10:#如果“分数”等于10,则运行这部分代码
打印(“太棒了”,姓名,“你得了满分!”)#打印陈述和姓名
elif分数>=6:#如果“分数”大于或等于6,则运行这部分代码
打印(“做得好,这里还有一些改进要做”,姓名,“你得到了”,分数“/10”)#然后打印语句和分数

elif分数使用
pickle
模块存储数据。将您的
user=>score
关系组织到字典中,然后调用
pickle.dump(filename,theDict)
将其保存到文件中


当您需要它时,调用dict=pickle.load(filename)
,它将从pickle文件加载数据。这种方法比设计自己的解析算法要好。

使用
pickle
模块来存储数据。将您的
user=>score
关系组织到字典中,然后调用
pickle.dump(filename,theDict)
将其保存到文件中


当您需要它时,调用dict=pickle.load(filename),它将从pickle文件加载数据。这种方法比你必须设计自己的解析算法要好。

如果你想将用户的分数保存到列表中

my_list = []
my_list.append(score)
在游戏开始之前,您可能还需要读取文件。然后,您需要使用文本文件中的分数填充列表

with open(class_number) as scorefile:
    for line in scorefile:
        my_list.append(line)
最后,当游戏结束时,您需要将用户的分数添加到文件中。在这种情况下,我将保持它的简单性,不包括一个人的名字作为一个例子,您仍然可以添加到列表中的行

f = open(class_number 'w')
f.write("\n" + score)
f.close()

然后,如果他们查看分数,只需打印“我的列表”的值,用新行分隔列表中的每个元素。

如果要将用户的分数保存到列表中

my_list = []
my_list.append(score)
在游戏开始之前,您可能还需要读取文件。然后,您需要使用文本文件中的分数填充列表

with open(class_number) as scorefile:
    for line in scorefile:
        my_list.append(line)
最后,当游戏结束时,您需要将用户的分数添加到文件中。在这种情况下,我将保持它的简单性,不包括一个人的名字作为一个例子,您仍然可以添加到列表中的行

f = open(class_number 'w')
f.write("\n" + score)
f.close()

然后,如果他们查看分数,只需打印my_列表的值,用新行分隔列表中的每个元素。

如果您想让它保持可读性,请将其写入json文件:

import json

your_dictonary = {"my_key":"one_value"}

str_to_save = json.dumps(your_dictonary)
# Then write it to a file as you did before
加载几乎同样简单:

json.loads(file_content) # after you read the file as usual

如果要使其保持可读性,请将其写入json文件:

import json

your_dictonary = {"my_key":"one_value"}

str_to_save = json.dumps(your_dictonary)
# Then write it to a file as you did before
加载几乎同样简单:

json.loads(file_content) # after you read the file as usual

如果您同意更改文件的外观,请尝试

在代码顶部,从文件中加载分数:

import json
with open('{}.txt'.format(class_number)) as f:
    scores = json.load(f)
scores[name] = score
with open('{}.txt'.format(class_number)) as f:
    json.dump(scores, f)
try:
    fileh = open(class_number, 'r')
    oldlines = fileh.readlines()
    fileh.close()
except IOError: # If we didn't find the file, there were no old scores
    oldlines = []
fileh = open(class_number, 'w')
fileh.writelines(updatedlines)
fileh.close()
然后,您可以修改词典中的分数并将其写回文件:

import json
with open('{}.txt'.format(class_number)) as f:
    scores = json.load(f)
scores[name] = score
with open('{}.txt'.format(class_number)) as f:
    json.dump(scores, f)
try:
    fileh = open(class_number, 'r')
    oldlines = fileh.readlines()
    fileh.close()
except IOError: # If we didn't find the file, there were no old scores
    oldlines = []
fileh = open(class_number, 'w')
fileh.writelines(updatedlines)
fileh.close()
此代码存储的分数不超过最新的分数,但您可以探索每个名称保存多个分数的选项。伊苏