简体   繁体   中英

Sorting lines by the second word on each line of text file, then displaying it

I have to sort a file into the highest scores that people have gained, to the lowest and display the sorted version of it in python. The file I currently have looks like this.

Bob: 0 /10

Bob: 1 /10

Jane: 9 /10

Drake: 5 /10

Dan: 4 /10

Josh: 1 /10

Dan: 5 /10

(excluding the empty lines)

How can I sort and display this on python?

If you have a file grades :

lines = grades.read().splitlines()
lines.sort(key=lambda line: int(line.split()[1]))

for line in lines:
    print line

You need to write code to read the file in a line at a time, skipping any blank lines, and to split the three interesting parts up. This can be done using a regular expression which is capable of extracting the name, mark and total from each line into a tuple.

So for each line you would get a tuple looking something like:

('Bob', '1', '10')

This tuple is then appended to a list of names. This list can then be sorted. In your example, all of the results are out of 10. But what if one was out of 20?

The following shows you one possible way you could do this:

import re

names = []

with open('grades.txt', 'r') as f_input:
    for line in f_input:
        if len(line) > 1:
            names.append(re.match(r'(.*?):\s*?(\d+)\s*?\/\s*?(\d+)', line).groups())

for name, mark, total in sorted(names, key=lambda x: float(x[1]) / float(x[2]), reverse=True):
    print "{} - {} out of {}".format(name, mark, total)

This would display the following:

Jane - 9 out of 10
Drake - 5 out of 10
Dan - 5 out of 10
Dan - 4 out of 10
Bob - 1 out of 10
Josh - 1 out of 10
Bob - 0 out of 10

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