python:添加到用户名
我对python相当陌生,我需要制作一个程序来询问10个问题,将分数保存到一个文件中,并允许有人从文件中读取分数 我的问题是:我需要检查做过测试的人是否在文件中有记录,如果有,我需要将他们的分数添加到记录的末尾 记录应如下所示:python:添加到用户名,python,Python,我对python相当陌生,我需要制作一个程序来询问10个问题,将分数保存到一个文件中,并允许有人从文件中读取分数 我的问题是:我需要检查做过测试的人是否在文件中有记录,如果有,我需要将他们的分数添加到记录的末尾 记录应如下所示: rows = str.split("\n") data1 = {} for row in rows: tmp = row.split(",") data1[tmp[0]] = tmp[1:] 名字,分数,分数,分数,分数, 等,以便使用逗号将其拆分 我也在寻找
rows = str.split("\n")
data1 = {}
for row in rows:
tmp = row.split(",")
data1[tmp[0]] = tmp[1:]
名字,分数,分数,分数,分数,
等,以便使用逗号将其拆分
我也在寻找最简单的答案,而不是最有效的。此外,如果您可以对代码进行注释,这将使它变得更容易。以下是我目前的代码:
import random
import math
import operator as op
import sys
import re
def test():
num1 = random.randint(1, 10)
num2 = random.randint(1, num1)
ops = {
'+': op.add,
'-': op.sub,
'*': op.mul,
}
keys = list(ops.keys())
rand_key = random.choice(keys)
operation = ops[rand_key]
correct_result = operation(num1, num2)
print ("What is {} {} {}?".format(num1, rand_key, num2))
while True:
try:
user_answer = int(input("Your answer: "))
except ValueError:
print("Only enter numbers!")
continue
else:
break
if user_answer != correct_result:
print ("Incorrect. The right answer is {}".format(correct_result))
return False
else:
print("Correct!")
return True
print("1. Are you a student?")
print("2. Are you a teacher?")
print("3. Exit")
while True:
try:
status = int(input("Please select an option:"))
except ValueError:
print("Please enter a number!")
else:
if status not in {1,2,3}:
print("Please enter a number in {1,2,3}!")
else:
break
if status == 1:
username=input("What is your name?")
while not re.match("^[A-Za-z ]*$", username) or username=="":
username=input(str("Please enter a valid name (it must not contain numbers or symbols)."))
print ("Hi {}! Wellcome to the Arithmetic quiz...".format(username))
while True:
try:
users_class = int(input("Which class are you in? (1,2 or 3)"))
except ValueError:
print("Please enter a number!")
else:
if users_class not in {1,2,3}:
print("Please enter a number in {1,2,3}!")
else:
break
correct_answers = 0
num_questions = 10
for i in range(num_questions):
if test():
correct_answers +=1
print("{}: You got {}/{} {} correct.".format(username, correct_answers, num_questions,
'question' if (correct_answers==1) else 'questions'))
if users_class == 1:
class1 = open("Class1.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class1.write(newRecord)
class1.close()
elif users_class == 2:
class2 = open("Class2.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class2.write(newRecord)
class2.close()
elif users_class == 3:
class3 = open("Class3.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class3.write(newRecord)
class3.close()
else:
print("Sorry, we can not save your data as the class you entered is not valid.")
编辑:
在“测试”功能之前添加此功能:
def writeUserScore(file, name, score):
with open (file, "r") as myfile:
s = myfile.read()
rows = s.split("\n")
data = {}
for row in rows:
tmp = row.split(",")
if len(tmp) >= 2: data[tmp[0]] = tmp[1:]
if name not in data:
data[name] = []
data[name].append(str(score))
output = ""
for name in data:
output = output + name + "," + ",".join(data[name]) + "\n"
handle = open(file, "w+")
handle.write(output)
handle.close()
然后,在“if users_class==1:”的位置执行以下操作:
对其他两个ifs执行相同的操作
让我知道你的想法
尝试使用字典保存现有文件数据 例如,读取名为“str”的变量中的文件。然后像这样做:
rows = str.split("\n")
data1 = {}
for row in rows:
tmp = row.split(",")
data1[tmp[0]] = tmp[1:]
当您获得新分数时,您应执行以下操作:
if username not in data1:
data1[username] = []
data1[username] = str(correct_answers)
并将数据保存回文件:
output = ""
for name in data1:
output = outupt + name + "," + ",".join(data1[name]) | "\n"
并将“输出”的内容保存到文件中
PS:如果不受文件格式的约束,可以使用JSON文件。如果你愿意,我可以告诉你更多
希望有帮助,
Alex首先,定义以下功能:
from collections import defaultdict
def read_scores(users_class):
"""
If the score file for users_class does not exist, return an empty
defaultdict(list). If the score file does exist, read it in and return
it as a defaultdict(list). The keys of the dict are the user names,
and the values are lists of ints (the scores for each user)
"""
assert 0 <= users_class <= 3
result = defaultdict(list)
try:
lines =open("Class%d.txt"%users_class,'r').readlines()
except IOError:
return result
for line in lines:
# this line requires python3
user, *scores = line.strip().split(',')
# if you need to use python2, replace the above line
# with these two lines:
# line = line.strip().split(',')
# user, scores = line[0], line[1:]
result[user] = [int(s) for s in scores]
return result
def write_scores(users_class, all_scores):
"""
Write user scores to the appropriate file.
users_class is the class number, all scores is a dict kind of dict
returned by read_scores.
"""
f = open("Class%d.txt"%users_class,'w')
for user, scores in all_scores.items():
f.write("%s,%s\n"%(user, ','.join([str(s) for s in scores])))
def update_user_score(users_class, user_name, new_score):
"""
Update the appropriate score file for users_class.
Append new_score to user_name's existing scores. If the user has
no scores, a new record is created for them.
"""
scores = read_scores(users_class)
scores[user_name].append(new_score)
write_scores(users_class, scores)
Class1.txt中将有两行:
菲尔,7,6,9
爱丽丝,6岁
我们将整个文件读入一个dict(实际上是一个defaultdict(list)),
并用更新的dict覆盖同一个文件。通过使用defaultdict(list),我们不必担心更新和添加记录之间的区别
还要注意,我们不需要单独的if/elif案例来读/写文件
“Scores%d.txt”%users\u class
为我们提供了文件名。那么第二部分是否在“if users\u class==1:”之后,替换之前的内容?或者它只替换“class1=open”(“class1.txt”,“a+”)。很抱歉打扰您,但我对编码非常陌生。这一切都在测试功能之前进行吗?在您使用update_user_score功能之前,defs可以在任何地方进行。如果你喜欢的话,把它们放在最上面。然后,删除末尾以“if users\u class==1”开头的所有内容:“将其替换为:update\u user\u score(users\u class,username,correct\u答案)
update_user_score(1, 'phil', 7)
update_user_score(1, 'phil', 6)
update_user_score(1, 'alice', 6)
update_user_score(1, 'phil', 9)