0

I have a text file, say:

cat 2    
dog 4  
bird 20  
animal 3

I want to read this file and sort like this (according to numbers):

cat 2  
animal 3  
dog 4              
bird 20 

Code tried so far:

def txtsort(self, _, line):
words = [] 
    for word in WORD_RE.findall(line):
    words.append(word)
words_ini = words[0]
count_ini = np.array(words[1])
count_sort = np.sort(count_ini,axis = 0,kind='quikstart', order = None)
bharath
  • 11
  • 2

2 Answers2

2

Suppose you have words in a list similar to:

words = [
    ('cat', 2),
    ('dog', 4),
    ('bird', 20),
    ('animal', 3)
]

result = sorted(words, key=lambda x: x[1])
Jivan
  • 21,522
  • 15
  • 80
  • 131
-1

You don't need external libraries for this. Just split each line and add it to a list, casting the second element as a number. Then sort the list by that element.

with open('file.txt') as f:
    result = [(a,int(b)) for line in f for a,b in line.split()]

result.sort(key=lambda x: x[1])
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97