Skip to content Skip to sidebar Skip to footer

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:

Solution 1:

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

Solution 2:

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

Post a Comment for "Sorting Lines By The Second Word On Each Line Of Text File, Then Displaying It"