从python中的文件中排序信息

时间:2015-01-23 09:09:36

标签: python sorting text-files

我有一个.txt文件,其中包含以下信息,用于显示用户名,然后是3个在测验中得分的分数:

callum,10,7,9
carl,10,10,10
hollie,1,4,7
brad,4,8,3
kyle,7,2,0

我希望sort按字母顺序显示用户名后的最高分。

2 个答案:

答案 0 :(得分:1)

  1. 阅读文件内容。
  2. 使用readlines()方法从文件中读取行。
  3. 使用split()获取姓名和分数。
  4. 添加字典:NameKeyValue为总分。
  5. 从结果字典中获取所有keys
  6. 用户sort()方法按字母排序列表。
  7. 按字母顺序打印结果。
  8. 代码

    p = "/home/vivek/Desktop/test_input.txt"
    result = {}
    with open(p, "rb") as fp:
        for i in fp.readlines():
            tmp = i.split(",")
            try:
                result[(tmp[0])] = eval(tmp[1]) + eval(tmp[2]) + eval(tmp[3]) 
            except:
                pass
    
    alphabetical_name =  result.keys()
    alphabetical_name.sort()
    
    for i in alphabetical_name:
        print "Name:%s, Highest score: %d"%(i, result[i])
    

    输出:

    $ python test.py 
    Name:brad, Highest score: 15
    Name:callum, Highest score: 26
    Name:carl, Highest score: 30
    Name:hollie, Highest score: 12
    Name:kyle, Highest score: 9
    

答案 1 :(得分:0)

所以我首先要隔离所有的行:

with open('filename') as f:
    lines = f.readlines()

所以我将继续假设我有一个名为line的列表,其中包含以下内容:

lines = ["callum,10,7,9","carl,10,10,10","hollie,1,4,7","brad,4,8,3","kyle,7,2,0"]

然后我将首先按名称对行进行排序

lines = sorted(lines)

然后,对于要隔离标记的每一行,对它们进行排序并将其打印回来:

for line in lines:
    #name is what there is before the first comma
    name = line[:line.find(",")]
    #marks are what there is after the second comma and are comma separated
    marks = line[line.find(",")+1:].split(",")
    #sort the marks
    marks = sorted(marks,key=int)

    #if you want to print only the highest
    print "%s,%s"%(name,marks[-1])