![](/img/trans.png)
[英]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.