python:添加到用户名

时间:2015-03-01 23:53:00

标签: 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.")

2 个答案:

答案 0 :(得分:1)

编辑:


在"测试"之前添加此功能。功能:

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()

之后,你有"如果users_class == 1:"这样做:

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

对其他两个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文件。如果你愿意,我可以告诉你更多关于这一点。

希望有所帮助, 亚历

答案 1 :(得分:1)

首先,定义这些功能:

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)), 并使用更新的dict覆盖该文件。通过使用defaultdict(list),我们不必担心区分更新和添加记录。

另请注意,我们不需要单独的if / elif案例来读取/写入文件。 "Scores%d.txt"%users_class为我们提供了文件的名称。