简体   繁体   中英

To sort a file which contains both strings and integers in python3

I have a text file which contains user name and their count as below:

[test1]:11
[test2]:1097
[test3]:461
[test4]:156
[test5]:16
[test6]:9
[test7]:568
[test8]:17
[test9]:373
[test10]:320

I want to sort my output in descending order and the output should look like:

[test2]:1097
[test7]:568
[test3]:461
[test9]:373
[test10]:320
[test4]:156
[test8]:17
[test5]:16
[test1]:11
[test6]:9

Please help me achieving this in python3.

I tried doing it like this..which is not working.

subprocess.Popen(['sort', '-n', '-r', 'Test.txt'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

data = '''[test1]:11
[test2]:1097
[test3]:461
[test4]:156
[test5]:16
[test6]:9
[test7]:568
[test8]:17
[test9]:373
[test10]:320'''

for line in sorted(data.splitlines(), key=lambda k: int(k.split(':')[-1]), reverse=True):
    print(line)

Prints:

[test2]:1097
[test7]:568
[test3]:461
[test9]:373
[test10]:320
[test4]:156
[test8]:17
[test5]:16
[test1]:11
[test6]:9

EDIT: with reading from file you can do this:

with open('Test.txt', 'r') as f_in:
    for line in sorted(f_in.readlines(), key=lambda k: int(k.split(':')[-1]), reverse=True):
        print(line.strip())

You can use built-in function sorted() (or list.sort() which is equivalent):

s = """[test1]:11
[test2]:1097
[test3]:461
[test4]:156
[test5]:16
[test6]:9
[test7]:568
[test8]:17
[test9]:373
[test10]:320"""
lst = s.splitlines()
sorted_lst = sorted(lst, key=lambda item: int(item[item.index(":") + 1:]), reverse=True)
print(sorted_lst)

Output:

['[test2]:1097', '[test7]:568', '[test3]:461', '[test9]:373', '[test10]:320', '[test4]:156', '[test8]:17', '[test5]:16', '[test1]:11', '[test6]:9']

How does it work .

Quote from docs :

Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons.

I my example I pass to key parameter next lambda expression :

lambda item: int(item[item.index(":") + 1:])

It's equivalent to function:

def func(item):
    return int(item[item.index(":") + 1:])

This function (or lambda) copy from source string chars after ":" symbol and cast result string to int.

Every sort iteration python will call this function to "cook" element before doing comparisons.

res =[]
with open('result.txt') as f:
    tmp=[]
    for i in f.readlines():
        tmp=i.strip('\n').split(':')
        res.append(tmp)

sol = sorted(res, key=lambda x:x[1])
with open('solution.txt','a+') as f:
    for i in sol:
        f.write(r'{}:{}'.format(i[0],i[1])+'\n')

Try this,

with open('file1.txt','r') as f:
    print(sorted([line.replace('\n','') for line in f], key = lambda x:int(x.replace('\n','').split(':')[-1]), reverse=True))

Output:

['[test2]:1097', '[test7]:568', '[test3]:461', '[test9]:373', '[test10]:320', '[test4]:156', '[test8]:17', '[test5]:16', '[test1]:11', '[test6]:9']

Note:

It will replace newline character ( \\n ) with empty string ( '' )

def dict_val(x):
...     return x[1]

###First Read the File
f = open('test.txt','r')
content = f.readlines()

# Now add contents of file to a dict
count_dict = {}
for line in content:
...     key,value = line.split(':')
...     count_dict[key] = value

### Now using sorted function to sort values.
sorted_x = sorted(count_dict.items(), key=dict_val)
print(sortex_x)


we need to specify the field on which we are going to sort using the -k option. For more details please refer to the link: https://unix.stackexchange.com/questions/77406/sort-only-on-the-second-column

Code :

import subprocess
process = subprocess.Popen(['sort', '-n', '-r', '-t:', '-k2,2', 'input.txt'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # start index 2 and end index =2 for sroting
stdout = process.communicate()[0]
print(stdout.decode('utf-8'))

Output :

[test2]:1097
[test7]:568
[test3]:461
[test9]:373
[test10]:320
[test4]:156
[test8]:17
[test5]:16
[test1]:11
[test6]:9

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