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
答案 0 :(得分:0)
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 namesort_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