简体   繁体   中英

Sorting txt lines numerically

I took txt file as input and i want to sort them numerically. How can i do? The input file as txt:

65 1 Hello
78 3 up
78 2 what's
65 2 world

i want the output as:

message 1:
    65 1 Hello
    65 2 world
message 2:
    78 2 what's
    78 3 up

First i need to sort first numbers, then i need to sort second numbers. I thought i can put every line in a list and then sort them. Then i need to write "message n:" before every text group. Finally i need to put them in a new txt file.

you can use List.sorted:

# Using readlines() 
file1 = open('./mytext.txt', 'r') 
Lines = file1.readlines() 
  

Lines.sort(key=lambda line: (int(line.split(" ")[0]),int(line.split(" ")[1])),reverse=False)


print(Lines)



temp=0
count=0
for i in Lines:
    value = int(i.split(" ")[0])
    if(value!=temp):
        count+=1
        print("message {0}:".format(count))
        print("    "+(i).replace("\n",""))
        temp=value
    else:
        print("    "+(i).replace("\n",""))
        temp=value
        

Output

在此处输入图像描述

IF you have to sort first in descending order using first-row value and then in ascending using the second-row value

This can be done by assigning negative to the second number

# Using readlines() 
file1 = open('./mytext.txt', 'r') 
Lines = file1.readlines()   

Lines.sort(key=lambda line: (int(line.split(" ")[0]),-int(line.split(" ")[1])),reverse=True)
    
print(Lines)    

temp=0
count=0
for i in Lines:
    value = int(i.split(" ")[0])
    if(value!=temp):
        count+=1
        print("message {0}:".format(count))
        print("    "+(i).replace("\n",""))
        temp=value
    else:
        print("    "+(i).replace("\n",""))
        temp=value

Output:

在此处输入图像描述

You can sort them after splitting into separate lines by 1st and second order numbers as:

sorted([line.split() for line in file_contents.split('\n')], key = lambda x:(int(x[0]), int(x[1])))

results in:

[['65', '1', 'Hello'],
 ['65', '2', 'world'],
 ['78', '2', "what's"],
 ['78', '3', 'up']]

Then you can play around with this list to have output to your liking: Hint. Go grab the unique 0th index values and change the message number when 0th index is changed. While it is unchanged concat all 2nd index values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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