简体   繁体   English

在python3中对包含字符串和整数的文件进行排序

[英]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. 请帮助我在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): 您可以使用内置函数sorted() (或list.sort() ):

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. list.sort()sorted()都有一个关键参数,用于指定在进行比较之前在每个列表元素上要调用的函数。

I my example I pass to key parameter next lambda expression : 在我的示例中,我将下一个lambda表达式传递给key参数:

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. 这个函数(或lambda)从源字符串复制字符 “:”符号和投结果字符串为int。

Every sort iteration python will call this function to "cook" element before doing comparisons. 每次排序迭代python都会在进行比较之前将该函数调用为“ cook”元素。

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 ( '' ) 它将取代换行符( \\n与空字符串)( ''

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. 我们需要使用-k选项指定要进行排序的字段。 For more details please refer to the link: https://unix.stackexchange.com/questions/77406/sort-only-on-the-second-column 有关更多详细信息,请参阅链接: https : //unix.stackexchange.com/questions/77406/sort-only-on-the-second-column

Code : 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 : Output

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

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

相关问题 对同时包含字符串和整数的列表进行排序 (Python) - Sort a list that contains both strings and integers (Python) Python - 读取包含字节和字符串的文件 - Python - Read a file which contains bytes and strings 在Python中从文本文件中选择整数/字符串并对其进行排序 - Select and sort integers/strings from a text file in Python 有没有办法对通过 Python 中由字符串和整数组成的类创建的对象进行排序? - Is there a way to sort objects created through classes that is made up of both strings and integers in Python? Python:如何使用字符串和整数的组合对数组进行排序 - Python: How to sort an Array with with a combination of Strings and Integers Python3中包含字典的列表的排序 - Sorting of list which contains dictionary in Python3 Python字符串和整数写入文件? - Python strings and integers to write to file? 在Python中,在包含字符串和浮点数的列表中查找最小值的最简单方法是什么? - In Python, what is the easiest way to find the smallest value in a list which contains both strings and floats? 将数字字符串列表转换为带有整数的元组 Python3 - Converting a list of strings of numbers to tuples with integers Python3 在列表中找到最小的整数,它有字符串和整数 - Find lowest integer in list, which has both strings and integers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM