【问题标题】:Sorting text file entries对文本文件条目进行排序
【发布时间】:2022-01-10 18:49:04
【问题描述】:

我正在尝试按每行中的第一个数字对 .txt 文件中的行进行排序。sample text file 我还想将每行中的第二个数字移到每行的末尾。这是我到目前为止的内容,但由于某种原因,这些行没有按两个文件之间的数字排序。

#combine files
filenames = ['detections_mandatory.txt','detections_other.txt']

lines = []
for names in filenames:
    with open(names) as infile:
        for line in infile:
            lines.append(line)

#write list out to new file

with open("detections.txt", "w") as det:

    det.write(''.join(sorted(lines, key=lambda x: int(x.strip()))))

【问题讨论】:

  • 您的代码对我有用。我唯一的问题是在对元素进行排序后,它不会在其后添加\n。我认为这可以通过添加到join\n 来完成。但无法重现您所说的问题
  • 我最终只是关闭并重新打开了我正在使用的所有文件,问题就自行解决了。我仍然不确定是否将每行中的第二个数字移到行尾

标签: python file sorting text script


【解决方案1】:

您可以split每一行并根据需要重新排列拆分的单词:

files = ['file1.txt', 'file2.txt']

lines = []
for file in files:
    with open(file, 'r') as f:
        lines.extend(map(lambda line: line.split(), f.readlines())) # store split lines
# lines now is a list of lists

lines.sort(key=lambda line: int(line[0])) # sort the lines

with open('output.txt', 'w') as f:
    for line in lines:
        print(' '.join((line[0], *line[2:], line[1])), file=f)

join 中的双括号不是多余的;可以用join([line[0], ...])代替,但不能省略内部的[]()

file1.txt:

5 0.420 0.373 0.009 0.261 0.260
3 0.552 0.190 0.158 0.017 0.786
10 0.706 0.693 0.104 0.878 0.934
8 0.685 0.756 0.915 0.950 0.626

file2.txt:

1 0.916 0.869 0.265 0.634 0.950
3 0.967 0.721 0.734 0.636 0.676
9 0.314 0.267 0.836 0.020 0.868
3 0.739 0.325 0.050 0.071 0.370

output.txt:

1 0.869 0.265 0.634 0.950 0.916
3 0.190 0.158 0.017 0.786 0.552
3 0.721 0.734 0.636 0.676 0.967
3 0.325 0.050 0.071 0.370 0.739
5 0.373 0.009 0.261 0.260 0.420
8 0.756 0.915 0.950 0.626 0.685
9 0.267 0.836 0.020 0.868 0.314
10 0.693 0.104 0.878 0.934 0.706

【讨论】:

  • 非常感谢,这正是我想要的!一个问题,*line[2:] 中的 * 到底是做什么的?
  • @CydniTurner 那是unpacking;比如lst = [1, 2, 3],那么写[0, *lst, 4]就等价于[0, lst[0], lst[1], lst[2], 4],而[0, lst[0], lst[1], lst[2], 4]又等价于[0, 1, 2, 3, 4]
猜你喜欢
  • 2011-10-15
  • 1970-01-01
  • 1970-01-01
  • 2019-09-30
  • 1970-01-01
  • 2013-03-16
  • 2014-05-27
  • 2023-04-09
相关资源
最近更新 更多