简体   繁体   English

如何以编程方式重新排列文本文件值

[英]How can I rearrange text file value programmatically

Problem statement:问题陈述:

Class    Confidence    Xmin   Ymin    Xmax  Ymax
9        0.9745781     45     8        39   49
6        0.9401682     1      1        79   52
3        0.0167890     34     7        90   45

This value will have in my file.这个值将在我的文件中。 I want to rearrange all data such as: I want to compare Xmin value.我想重新排列所有数据,例如:我想比较 Xmin 值。 If Xmin value is small then Xmin line will write in the Top i mean ascending order.如果 Xmin 值很小,那么 Xmin 行将写在顶部,我的意思是升序。

Expected output:预期输出:

Class    Confidence    Xmin   Ymin    Xmax  Ymax
6        0.9401682     1      1        79   52
3        0.0167890     34     7        90   45
9        0.9745781     45     8        39   49

How can I do this programmatically using python?如何使用 python 以编程方式执行此操作? All data have text file and after doing this I want to save value same format in text file.所有数据都有文本文件,这样做之后我想在文本文件中保存相同格式的值。

If file.txt contains:如果file.txt包含:

Class    Confidence    Xmin   Ymin    Xmax  Ymax
9        0.9745781     45     8        39   49
6        0.9401682     1      1        79   52
3        0.0167890     34     7        90   45

Then running this script:然后运行这个脚本:

with open('file.txt', 'r') as f_in, \
    open('file_out.txt', 'w') as f_out:
    f_out.write(next(f_in))  # skip the header, write it directly to output file
    f_out.write('\n'.join(line.strip() for line in sorted(f_in, key=lambda k: int(k.split()[2]))))

will produce file_out.txt :将产生file_out.txt

Class    Confidence    Xmin   Ymin    Xmax  Ymax
6        0.9401682     1      1        79   52
3        0.0167890     34     7        90   45
9        0.9745781     45     8        39   49

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM