[英]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 . 它是如何工作的 。
Both
list.sort()
andsorted()
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.