Python添加用户名

2024-10-01 00:30:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python相当陌生,我需要做一个程序来问10个问题,将分数保存到一个文件中,并允许有人从文件中读取分数。你知道吗

我的问题是:我需要检查做过测试的人是否在文件中有记录,如果有,我需要把他们的分数加到记录的末尾。你知道吗

记录应如下所示:

名字,分数,分数,分数,分数, 等等,这样就可以用逗号将它们分开。你知道吗

我也在寻找最简单的答案,而不是最有效的。另外,如果您可以对代码进行注释,这将使它变得更容易。以下是我目前的代码:

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.")

Tags: inimportinputifusernamenotelse分数
2条回答

首先,定义这些功能:

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)

现在,在代码的最后一部分(实际上是写分数的地方)变得简单多了。下面是一个写分数的例子:

update_user_score(1, 'phil', 7)
update_user_score(1, 'phil', 6)
update_user_score(1, 'alice', 6)
update_user_score(1, 'phil', 9)

Class1.txt中将有两行: 菲尔,7,6,9 爱丽丝,6岁

我们将整个文件读入一个dict(实际上是一个defaultdict(list)), 通过使用defaultdict(list),我们不必担心更新和添加记录之间的区别。你知道吗

还要注意的是,我们不需要单独的if/elif案例来读/写文件。"Scores%d.txt"%users_class提供文件名。你知道吗

编辑:


在“test”函数之前添加此函数:

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\u class==1:”,请执行以下操作:

writeUserScore("Class1.txt", username, str(correct_answers))

对另外两个if也一样。你知道吗

让我知道你的想法!你知道吗


尝试使用字典保存现有文件数据。你知道吗

例如,读取名为“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"

并将“output”的内容保存到文件中。你知道吗

PS:如果您不受文件格式的约束,那么可以使用JSON文件。如果你愿意,我可以告诉你更多。你知道吗

希望有帮助, 亚历克斯

相关问题 更多 >