简体   繁体   中英

How to sort data from a file to the top 5 scores

I am not sure how to get my file to sort and display the top 5 scores from my text file. Text file below :

24fred
23alan
24bert
28dan
11orange
17purple
16dave
22andy 

The code which I am using to write to the file.

Tried using sort but can't get it to display only the top 5 scores.

file = open("Score.txt", "a")
file.write(str(name))
file.write(str(Score))
file.write("\n")
file.close

the file will print out sorted and only showing the top 5

You can use the following sample:

import re

pat = re.compile(r"^(\d+)(\D+)$")
def sort_crit(i):
    m = pat.match(i)
    return - int(m.group(1)), m.group(2)


with open("Score.txt",'r') as f:
  lines = [line.rstrip() for line in f]
  lines.sort(key = sort_crit)
  with open('Sorted_score.txt', 'w') as f:
    for item in lines:
        f.write("%s\n" % item)

input:

$ more Score.txt
24fred
23alan
24bert
28dan
28abc
11orange
17purple
16dave
22andy

output:

$ more Sorted_score.txt
28abc
28dan
24bert
24fred
23alan
22andy
17purple
16dave
11orange

Explanations:

  • re.compile(r"^(\\d+)(\\D+)$") will be used to extract individually the score and the name
  • sort_crit(i) will return the double sorting criteria based first on the score in reverse order (note the - ), followed by the name in alphabetic order
  • You open the input file and store all the lines in an array
  • You sort the lines using the sorting function you have defined
  • you output them in a new file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM