按文本文件每行的第二个单词对行进行排序,然后显示它 [英] Sorting lines by the second word on each line of text file, then displaying it
问题描述
我必须将文件分类为人们获得的最高分数,也要分类为最低分数,并以python显示其排序版本. 我当前拥有的文件如下所示.
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)
如何在python上进行排序和显示?
How can I sort and display this on python?
推荐答案
您需要编写代码以一次一行读取文件,跳过任何空白行,并将三个有趣的部分拆分开.这可以使用正则表达式来完成,该正则表达式能够从每行中提取名称,标记和总计到元组中.
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')
然后将该元组附加到名称列表中.然后可以对该列表进行排序.在您的示例中,所有结果均不超过10.但是,如果结果不超过20怎么办?
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)
这将显示以下内容:
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
这篇关于按文本文件每行的第二个单词对行进行排序,然后显示它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!