Python:读取文件并检查重复的字符串

Python:读取文件并检查重复的字符串,python,dictionary,Python,Dictionary,我的代码有点复杂,所以首先我要解释一下。基本上,我正在尝试创建一个简单的算术游戏,向用户/学生提问10个随机数从1到10的问题。然后,该数据(其名称和分数为10分)以以下格式写入名为class_a.txt的文件: Student_Name,7 Another_Person,5 然后我想读回class_a.txt。然而,当我读回它时,我需要将所有读回的信息存储在字典中。我目前正在这样做: def updateScores(): for line in fhandle: finder =

我的代码有点复杂,所以首先我要解释一下。基本上,我正在尝试创建一个简单的算术游戏,向用户/学生提问10个随机数从1到10的问题。然后,该数据(其名称和分数为10分)以以下格式写入名为class_a.txt的文件:

Student_Name,7
Another_Person,5
然后我想读回class_a.txt。然而,当我读回它时,我需要将所有读回的信息存储在字典中。我目前正在这样做:

def updateScores():
for line in fhandle:
    finder = line.find(",")
    newKey = line[0:finder]
    newValue = line[finder+1:len(line)-1]
    scores_content[newKey] = newValue
Student_A,6
Student_A,5
在已打开类_a.txt文件进行读取操作后调用函数的位置。并且已经定义了内容。但是,如果一名学生做了两次测验,那么文件可能如下所示:

def updateScores():
for line in fhandle:
    finder = line.find(",")
    newKey = line[0:finder]
    newValue = line[finder+1:len(line)-1]
    scores_content[newKey] = newValue
Student_A,6
Student_A,5
然后,当我读回并打印词典时,它只会返回:

['Student_A':'5']
在本例中,我不希望返回键Student_A,但它的值是5和6

基本上,我需要知道如何从文件中读取数据,当出现重复名称时,将两个分数作为值添加到字典中的键中。这就是我到目前为止所尝试的

import random

username = input("Enter students name: ")

while username.isalpha() == False:
    print ("Invalid name for student entered")
    username = input("Enter students name: ")

score = 0
answer = 0

for i in range(10):
    numOne = random.randint(1,10)
    numTwo = random.randint(1,10)

    operators = (" + "," - "," * ")
    operator = random.choice(operators)

    if operator == " + ":
        answer = numOne + numTwo
    elif operator == " - ":
        answer = numOne - numTwo
    elif operator == " * ":
        answer = numOne * numTwo

    question = "What is " + str(numOne) + operator + str(numTwo) + "? "

    user_answer = int(input(question))

    if user_answer == answer:
        score = score + 1
        print ("That is correct!")
    else:
        print ("That is incorrect!")

print (username + " you got " + str(score) + " out of 10")


user_class = input("What class is the student in (a/b/c)? ")
user_class = user_class.lower()

classes = ('a','b','c')

while user_class not in classes:
    print ("Invalid class entered")
    user_class = input("What class is the student in (a/b/c)? ")

if user_class == "a":
    fhandle = open("class_a.txt","a")
    fhandle.write(username.capitalize() + "," + str(score) + "\n")
elif user_class == "b":
    fhandle = open("class_b.txt","a")
    fhandle.write(username.capitalize() + "," + str(score) + "\n")
else:
    fhandle = open("class_c.txt","a")
    fhandle.write(username.capitalize() + "," + str(score) + "\n")

fhandle.close()


def updateScores():
    for line in fhandle:
        finder = line.find(",")
        newKey = line[0:finder]
        newValue = line[finder+1:len(line)-1]
        scores_content[newKey] = newValue
        for line in fhandle:
            newValues = []
            finderTwo = line.find(",")
            newKeyTwo = line[0:finderTwo]
            newValueTwo = line[finderTwo+1:len(line)-1]
            if newKeyTwo == newKey:
                newValues.append(newValue)
                newValues.append(newValueTwo)
                scores_content[newKey] = newValues
            else:
                print("No duplicate found for current line",line)
                scores_content[newKey] = newValue
    print(scores_content)

user_class = input("What classes results would you like to view (a/b/c)? ")
while user_class not in classes:
    user_class = input("Invalid class entered\n" + "What classes results would you like to view (a/b/c)? ")

print("What sorting method would you like to use?" + "\nA = Alphabetically" + "\nB = Average score maximum to minimum" + "\nC = Maximum to minimum")

method = input("Enter a sorting method: ").lower()
while method not in classes:
    method = input("Invalid method entered\n" + "Enter a sorting method: ")

scores_content = {}
if user_class == "a":
    fhandle = open("class_a.txt","r")
    updateScores()
elif user_class == "b":
    fhandle = open("class_b.txt","r")
    updateScores()
else:
    fhandle = open("class_c.txt","r")
    updateScores()
fhandle.close()

您需要将值存储在列表中,因为字典不能有重复的键

换句话说,您需要
{'Student_A':[7,6],'Student_B':[5]}
,请尝试以下操作:

results = {} # this is an empty dictionary
with open('results.txt') as f:
   for line in f:
     if line.strip(): # this skips empty lines
        student,score = line.split(',')
        results.setdefault(student.strip(), []).append(int(score.strip()))

print(results) # or you can do this:
for student,scores in results.iteritems():
    print('Scores for: {}'.format(student))
    for score in scores:
        print('\t{}'.format(score))

FWIW,已经有很多关于这个的问题被问到了,所以你可以通过这些问题得到一些有用的想法。Burhan Khalid已经回答了你问的问题,但是我注意到你的代码还有另一个问题。fhandle:循环中的内部
for行将读取文件的所有行,将文件光标保留在文件的末尾,因此,当fhandle:
循环中的外部
for行尝试读取文件时,将不会得到任何结果。您可以使用
.seek()
方法重置文件位置,但只需读取一次文件并将文件数据存储在行列表中可能更简单。