[英]How to check each line of a text file for a string and print all lines with occurrences of that word to a new text file?
[英]Sorting lines by the second word on each line of text file, then displaying it
我必须将文件按人们获得的最高分数排序,然后按最低分数排序,然后在python中显示该文件的排序版本。 我当前拥有的文件如下所示。
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上排序和显示?
如果您有文件 grades
:
lines = grades.read().splitlines()
lines.sort(key=lambda line: int(line.split()[1]))
for line in lines:
print line
您需要编写代码来一次一行地读取文件,跳过任何空白行,并将三个有趣的部分拆分开。 这可以使用正则表达式来完成,该正则表达式能够从每一行中提取名称,标记和总计到元组中。
因此,对于每一行,您将获得一个类似以下内容的元组:
('Bob', '1', '10')
然后将此元组附加到名称列表中。 然后可以对该列表进行排序。 在您的示例中,所有结果均不超过10。但是如果结果不超过20怎么办?
下面显示了一种可能的方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.