Python 如何对文件中的特定信息进行排序

Python 如何对文件中的特定信息进行排序,python,file,sorting,text-files,Python,File,Sorting,Text Files,我有一个预先制作的文本文件,里面有人的名字和分数。他们每个人都有三个分数,每个分数由一个标签隔开 John 12 13 21 Zack 14 19 12 Tim 18 22 8 Jill 13 3 22 现在,我的目标是按字母顺序对名字进行排序,只显示最高分数。看起来像这样: Jill 22 John 21 Tim 18 Zack 19 文件排序后,我想在python shell上打印它。我定义了代

我有一个预先制作的文本文件,里面有人的名字和分数。他们每个人都有三个分数,每个分数由一个标签隔开

John    12    13    21
Zack    14    19    12
Tim     18    22    8
Jill    13    3     22
现在,我的目标是按字母顺序对名字进行排序,只显示最高分数。看起来像这样:

Jill   22
John   21
Tim    18
Zack   19
文件排序后,我想在python shell上打印它。我定义了代码,因为我将把它实现到我创建的其他代码中

from operator import itemgetter

def highscore():
    file1 = open("file.txt","r")
    file1.readlines()
    score1 = file1(key=itemgetter(1))
    score2 = file1(key=itemgetter(2))
    score3 = file1(key=itemgetter(3))


def class1alphabetical():
    with open('file.txt') as file1in:
        lines = [line.split('/t') for line in file1in]
        lines.sort()
    with open('file.txt', 'w') as file1out:
        for el in lines:
            file1out.write('{0}\n'.format(' '.join(el)))
    with open('file.txt','r') as fileqsort:
        for line in file1sort:
            print(line[:-1])
        file1sort.close

classfilealphabetical()
我使用了其他问题的信息,如:和


然而,我现在仍然在做什么。

哇,你做的事情似乎有点太复杂了

这是一个粗略的想法

#this will get your folks in alpha
lines = f.readlines()
lines.sort()

#now, on each line, you want to split (that attrgetter is too complicated and
#blows up if <> 3 grades.

# use the special feature of split() with no parameter to remove all spaces and \t characters
fields = line.split()
name, grades = fields[0], fields[1:]

#cast your grades to integers  
grades = [int(grade) for grade in grades]

#sort and pick the last one
grades.sort()
highest = grades[-1]

#or... use max as suggested
highest = max(grades)

#write to output file....

在排序列表中列出行后,请尝试以下操作:

output = ["{} {}".format(i[0], max(i[1:], key=int)) for i in lines]

for i in output:
    print i

Jill 22
John 21
Tim 22
Zack 19
输出
是使用

花括号(“
{}
”)由传递给
str.format()
的参数替换。本例中的
str
“{}{}”


max
函数采用一个关键字参数“key”,如上所示,它允许您指定一个函数,以应用于给定给
max
的iterable中的每个项(本例中的iterable为i[1:])。我使用了
int
,因为列表中的所有项目都是字符串(包含数字),必须转换为
int
s。

这很容易通过一些内置函数和交互来实现:

代码:

#!/usr/bin/env python


from operator import itemgetter


scores = """\
John\t12\t13\t21\n
Zack\t14\t19\t12\n
Tim\t18\t22\t8\n
Jill\t13\t3\t22"""


datum = [x.split("\t") for x in filter(None, scores.split("\n"))]
for data in sorted(datum, key=itemgetter(0)):
    name, scores = data[0], map(int, data[1:])
    max_score = max(scores)
    print "{0:s} {1:d}".format(name, max_score)
$ python -i scores.py 
Jill 22
John 21
Tim 22
Zack 19
>>> 
输出:

#!/usr/bin/env python


from operator import itemgetter


scores = """\
John\t12\t13\t21\n
Zack\t14\t19\t12\n
Tim\t18\t22\t8\n
Jill\t13\t3\t22"""


datum = [x.split("\t") for x in filter(None, scores.split("\n"))]
for data in sorted(datum, key=itemgetter(0)):
    name, scores = data[0], map(int, data[1:])
    max_score = max(scores)
    print "{0:s} {1:d}".format(name, max_score)
$ python -i scores.py 
Jill 22
John 21
Tim 22
Zack 19
>>> 

有两项任务:

  • 只保留最高分
  • 按名称字母顺序对行排序
  • 下面是一个独立脚本,它删除除最高分数之外的每一行的所有分数:

    #!/usr/bin/env python3
    import sys
    import fileinput
    
    try:
        sys.argv.remove('--inplace') # don't modify file(s) unless asked
    except ValueError:
        inplace = False
    else:
        inplace = True # modify the files given on the command line
    
    if len(sys.argv) < 2:
        sys.exit('Usage: keep-top-score [--inplace] <file>')
    
    for line in fileinput.input(inplace=inplace):
        name, *scores = line.split() # split on whitespace (not only tab)
        if scores:
            # keep only the top score
            top_score = max(scores, key=int)
            print(name, top_score, sep='\t')
        else:
            print(line, end='') # print as is
    

    要打印按名称排序的行,请执行以下操作:

    $ sort -k1 class6Afile.txt
    
    sort
    命令的结果取决于您当前的语言环境,例如,您可以使用
    LC_ALL=C
    按字节值排序

    或者,如果您想要Python解决方案:

    #!/usr/bin/env python
    import sys
    from io import open
    
    filename = sys.argv[1] 
    with open(filename) as file:
        lines = file.readlines() # read lines
    
    # sort by name
    lines.sort(key=lambda line: line.partition('\t')[0])
    
    with open(filename, 'w') as file:
        file.writelines(lines) # write the sorted lines
    
    名称在此处按Unicode文本排序。您可以提供文件中使用的显式字符编码,否则将使用默认(基于您的区域设置)编码

    例如:

    $ python3 keep_top_score.py class6Afile.txt
    
    $ python sort_inplace_by_name.py class6Afile.txt
    
    结果
    请将代码放在此处,而不是链接图像
    readlines()
    return
    s a
    列表
    ,而不是修改文件迭代器,因此这是一个开始。一般建议您避免仅在绝对必要时读取/写入文件。这是因为磁盘操作比内存操作慢得多。读取文件一次,处理所有数据,然后写回文件。虽然如果你只想“打印”,你甚至不需要写回文件!其他答案都很好,但这一个是写在一种方式,OP将最有可能更好地理解,+1。冷静的无参数分裂,不知道。比我的if foo.strip()好得多,应该只使用
    highest=max(grades)
    。谢谢!但是,我的代码仍然会出现很多错误,因为字段超出了范围?就像在IndexError中一样?你有没有可能有空行?如果你这样做的话,你需要考虑这些。发布您的输出。您还可以围绕以下代码执行此操作:try:Exception,e:import pdb pdb.set_trace()。这将在出现异常时启动调试器,您可以四处窥探