Jack
Jack

Reputation: 29

Python 3.6.5 How to display the top5 scores from a file with names?

How do you display the top 5 scores with the players names from an external text file which looks like this:

Fred's score: 12
Bob's score: 14
Amy's score: 17
Adam's score: 11
Caitlin's score: 13 
tom's score: 19

I wrote this code to store the scores:

from random import randint
score1 = randint(1,20)
score2 = randint(1,20)
user1 = (input("What is your name? "))
user2 = (input("What is your name? "))

if score1 > score2:
    f = open("test.txt","a")
    f.write("\n")
    f.write(user1)
    f.write(" 's score: ")
    f.write(str(score1))
    f.close()

if score1 < score2:
    f = open("test.txt","a")
    f.write("\n")
    f.write(user2)
    f.write(" ,s score: ")
    f.write(str(score2))
    f.close()

Upvotes: 0

Views: 7967

Answers (4)

Kian
Kian

Reputation: 1350

This could be another solution if you extract your score file to a dictionary:

scores  = {}  
with open('score_file.txt', 'r') as fs: # open and
    for line in fs.readlines():   #read file all lines
        scores[int(line.split(':')[1].strip())] = line.split("'")[0].strip()

#scores = {12:'Fred',14:'Bob',17:'Amy',11:'Adam',13:'Caitlin',19:'tom', 10:'x'}
Tops = {}
for i in range(5):
    Tops[scores[max(scores.keys())]]= max(scores.keys())
    del scores[max(scores.keys())]
print Tops

and you should have:

{'Amy': 17, 'Fred': 12, 'Bob': 14, 'Caitlin': 13, 'tom': 19}

Upvotes: 0

It might be easiest to use a dictionary to keep the name and associated score. If the contents of the file is always <name>'s score: <value> then this should work:

d = {}  # dictionary to hold the data

with open('test.txt', 'r') as f: # open and
    for line in f.readlines():   # read file lines

        # assign the name as key to the score's value
        d[line.split("'")[0].strip()] = int(line.split(':')[1].strip())

# sort the list and slice the top 5 
print(sorted(d.items(), key=lambda x: x[1])[::-1])[:5]

should give you a list of the top 5 scores with their associated name:

[('tom', 19), ('Amy', 17), ('Bob', 14), ('Caitlin', 13), ('Fred', 12)]

Upvotes: 1

seayak
seayak

Reputation: 224

Here's a straight-forward approach:

with open('file.csv', 'r') as score_file:
    scores = [ line.strip().split(' ') for line in score_file ]

scores.sort(key=lambda x: x[2], reverse=True)

for i in range(5):
    if i == len(scores):
        break
    print(' '.join(scores[i]))

Upvotes: 0

ShlomiF
ShlomiF

Reputation: 2905

I'd just read the whole file, parse out the scores, sort, and take the top 5.
Something like this:

file_path = "/path/to/file.txt"
with open(file_path, 'r') as f:
    file_lines = f.readlines()
names_and_scores = [(l.strip().split(' ')[0], float(l.strip().split(' ')[2])) for l in file_lines]
names_and_scores.sort(key=lambda x: x[1], reverse=True)
print(names_and_scores[:5])

Does that work for you?
Good luck!

Upvotes: 0

Related Questions