【问题标题】:Python: Reading file and checking for repeated string [duplicate]Python:读取文件并检查重复的字符串[重复]
【发布时间】:2016-02-12 09:40:09
【问题描述】:

我的代码有点复杂,所以我先解释一下。基本上,我正在尝试创建一个简单的算术游戏,向用户/学生询问 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

在打开 class_a.txt 文件进行读取操作后调用函数的位置。并且 score_content 已经定义。但是,如果一个学生做两次测验,那么文件可能如下所示:

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

【问题讨论】:

  • FWIW,关于这个GCSE Computing programming task,已经有 许多 个问题被问到了,所以通过查看这些问题,您可能会得到一些有用的想法。
  • Burhan Khalid 已回答您提出的问题,但我注意到您的代码存在另一个问题。内部for line in fhandle: 循环将读取文件的所有行,将文件光标留在文件末尾,因此当外部for line in fhandle: 循环下一次尝试从文件中读取时,它将一无所获。您可以使用.seek() 方法重置文件位置,但读取文件一次并将文件数据存储在行列表中可能更简单。

标签: python dictionary


【解决方案1】:

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

换句话说,你需要{'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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-22
    • 2014-05-08
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多