Hello

In my program I have a text file that I read from and write to. However, I would like to display the contents of the text file in an alligned and sorted manner. The contents currently read-
name, score
name, score
Would I have to convert this information into lists in order to be able to do this? If so, how do I go about doing this?

This is the code where the contents of the text file is read and printed-

elif userCommand == 'V':
        print "High Scores:"
        scoresFile = open("scores1.txt", 'r')
        scores = scoresFile.read().split("\n")
        for score in scores:
            print score
        scoresFile.close()

Thankyou

I should have included that. Sorted by score, smallest to largest. I'm sorry!

In that case, you must first parse each line to get the score and convert it to a number. Here is how you can do this (between lines 4 and 5)

indexes = sorted((float(s.split()[-1]), i) for (i, s) in enumerate(scores))
scores = [scores[i] for (x, i) in indexes]

Another way to do this is

scores = sorted(scores, key=line_score)

where line_score is defined independently

def line_score(line):
   return float(line.rstrip().split()[-1])

Edited 6 Years Ago by Gribouillis: n/a

I just attempted the first method you provided and got an error message: list indices must be integers, not tuples.
Does this have something to do with the variable names in the code you provided?

I just attempted the first method you provided and got an error message: list indices must be integers, not tuples.
Does this have something to do with the variable names in the code you provided?

No, I edited the code since my first post. It should work now.

Should the second line of your code be indented?
This is what I have done- I think I have to change some of the variable names?

elif userCommand == 'V':
        print "High Scores:"
        scoresFile = open("scores1.txt", 'r')
        scores = scoresFile.read().split("\n")
        indexes = sorted((float(s.split()[-1], i) for (i,s) in enumerate(scores)
        scores = [scores[i] for (x,i) in indexes]
        for score in scores:
            print score
        scoresFile.close()

Also, could you explain what the code does, I don't really understand it.
Thank you for your help

Ok, here is an example

scores = ["playerC 34", "playerA 12", "playerD 3", "playerB 10"]

first = [x.strip().split() for x in scores]
print(first) # ---> [['playerC', '34'], ['playerA', '12'], ['playerD', '3'], ['playerB', '10']]

second = [(float(x.strip().split()[-1]), i) for (i, x) in enumerate(scores)]
print(second) # ---> [(34.0, 0), (12.0, 1), (3.0, 2), (10.0, 3)]

third = sorted(second, reverse = True)
print(third) # ---> [(34.0, 0), (12.0, 1), (10.0, 3), (3.0, 2)]

fourth = [scores[i] for (x, i) in third]
print(fourth) # ---> ['playerC 34', 'playerA 12', 'playerB 10', 'playerD 3']

If I understand this right, you could also use this approach ...

# name, score text for the test
test_text = """\
John, 88
Mark, 75
Frank, 79
Bob, 56"""

fname = "myscores.txt"
#write the multiline text to a test file
fout = open(fname, "w")
fout.write(test_text)
fout.close()

# read the file back as single string
fin = open(fname, "r")
score_str = fin.read()
fin.close()

# create a list of (score, name) tuples
score_name = []
for line in score_str.split('\n'):
    # separator is comma and space char
    name, score = line.split(', ')
    # score is a numeric value
    score = int(score)
    score_name.append( (score, name) )

print score_name

"""my output -->
[(88, 'John'), (75, 'Mark'), (79, 'Frank'), (56, 'Bob')]
"""

print '-'*60

# show as a table (low score first)
for score, name in sorted(score_name):
    print "%-15s %s" % (name, score)
    
"""my output -->
Bob             56
Mark            75
Frank           79
John            88
"""

Yes this is exactly what I am after.
So I have written to the file using this code:

elif saveScore == 'Y':
                    print "Saving high scores file..."
                    highScore = name + ", " + str(numGuesses)
                    highScore = str(highScore)
                    scoresFile = open("scores1.txt", 'a')
                    scoresFile.write('\n' + highScore)
                    scoresFile.close()

And I am reading the file using the code you have provided, however I am not sure if I have done it right:

elif userCommand == 'V':
        print "High Scores:"
        scoresFile = open("scores1.txt", 'r')
        score_str = scoresFile.read()
        scoresFile.close()
        
        score_name = []
        for line in score_str.split('\n'):
            name, score = line.split(',')
            score = int(score)
            score_name.append((score, name)
        for score, name in sorted(score_name):
             print "%-15s %s" % (name, score)

Would you be able to check over this code and tell me what I have done wrong.
Thank you so much

That code worked perfectly, however, one problem has been created. If you view the high scores before playing the game, the input name from the user is overwritten by the first name in the file. So then when you play the game it uses that name instead of the users input. This only occurs when the scores are viewed first. If it is played straight away, the users input is used.

This is all my code, I hope you can help
Thank you very much!

import random

print "Welcome to the Great CP1200 Guessing Game! \nWritten by ..., March 2010 \nSee if you can get a high score"
name = raw_input("What is your name: ")

while True:
    print "\nMenu: \n(V)iew High Scores \n(P)lay Game \n(Q)uit"
    userCommand = raw_input(">>>")
    userCommand = userCommand.upper()

    if userCommand == 'Q':
        print "Thankyou for playing."
        break

    elif userCommand == 'V':
        print "High Scores:"
        scoresFile = open("scores1.txt", 'r')
        score_str = scoresFile.read()
        scoresFile.close()
        score_name = []
        for line in score_str.split('\n'):
            name, score = line.split(', ')
            score = int(score)
            score_name.append( (score, name) )
        for score, name in sorted(score_name):
            print "%-18s %s" % (name, score)
            
    elif userCommand == 'P':
        smallestNum = 1
        largestNum = 42
        randomNumber = random.randint(smallestNum, largestNum)
        numGuesses =0

        while True:
            numGuesses += 1
            userGuess = input("Please enter a number between %s and %s:" % (smallestNum, largestNum))
            
            if userGuess <smallestNum or userGuess >largestNum:
                print "Invalid guess."
            elif userGuess > randomNumber:
                print "My number is lower"
            elif userGuess < randomNumber:
                print "My number is higher"
            else:
                print "You got it! \nWell done,", name + ". " "You guessed it in", numGuesses, "guesses. \n"
                saveScore = raw_input("Would you like to save your score? (Y)es or (N)o: ")
                saveScore = saveScore.upper()
                if saveScore == 'N':
                    break
                elif saveScore == 'Y':
                    print "Saving high scores file..."
                    highScore = name + ", " + str(numGuesses)
                    highScore = str(highScore)
                    scoresFile = open("scores1.txt", 'a')
                    scoresFile.write('\n' + highScore)
                    scoresFile.close()
                    break
            
    else:
        print "Invalid menu choice."

Edited 6 Years Ago by jozz3: n/a

How do you delete posts?

Edited 6 Years Ago by jozz3: n/a

This question has already been answered. Start a new discussion instead.