[英]How to sort out a text file in python using numbers in the text file
我有以下文本文件:
345 eee
12 nt
3 s
9 test
我怎样才能使它按照数字顺序与那里的文本进行排序?
我希望的输出是
345 eee
12 nt
9 test
3 s
注意:我正在从文本文件中获取数据
45 eee
12 nt
945 test
344 s
45 gh
当前代码
信用:@CypherX
import pandas as pd
s = """
345 eee
1200 nt
9 test
-3 s
"""
# Custom Function
def sort_with_digits(s, ascending = True):
lines = s.strip().split('\n')
df = pd.DataFrame({'Lines': lines})
df2 = df.Lines.str.strip().str.split(' ', expand=True).rename(columns={0: 'Numbers', 1: 'Text'})
df['Numbers'] = df2['Numbers'].astype(float)
df['Text'] = df2['Text'].str.strip()
df.sort_values(['Numbers', 'Text'], ascending = ascending, inplace=True)
return df.Lines.tolist()
print(s)
sort_with_digits(s, ascending = True) # this is your output
使用 python 并且没有系统调用:
# This is the function to amend when you want to change the ordering
def key_function(line):
# To sort by the first number when there is a space
return int(line.split()[0])
要提取以该行开头的任何数字,您可以使用正则表达式
def key_function(line):
match = re.match('^\d+', line)
if match:
return int(match.group())
else:
return 0
那么剩下的方法都是一样的
with open(file_name, 'r') as f:
# Read all lines into a list
lines = f.readlines()
with open(file_name, 'w') as f:
# Sort all the lines by "key_function"
for line in sorted(lines, key=key_function, reverse=True):
f.write(line + '\n')
这是bash中的解决方案。 您可以使用子进程在python中运行它。
sort -k1 -r -n file > new_file
将此与 pyhton 子进程一起使用
import subprocess
# Simple command
subprocess.Popen(['sort -k1 -r -n test.txt'], shell=True)
编辑:稍后描述的 OP 要求首先按数字排序,然后按后面的其余文本排序。 现在的解决方案反映了这一要求。
我编写了一个自定义函数(
sort_with_digits
),它找出数字,然后使用pandas
库相应地对行进行排序。 您所要做的就是:
#read-in data from a text file:
with open('input.txt', 'r') as f:
s = f.read()
sort_with_digits(s, ascending = True)
s = """
345 eee
12 nt
9 test
3 s
"""
import pandas as pd
# Custom Function
def sort_with_digits(s, ascending = True):
lines = s.strip().split('\n')
df = pd.DataFrame({'Lines': lines})
df2 = df.Lines.str.strip().str.split(' ', expand=True).rename(columns={0: 'Numbers', 1: 'Text'})
df['Numbers'] = df2['Numbers'].astype(float)
df['Text'] = df2['Text'].str.strip()
df.sort_values(['Numbers', 'Text'], ascending = ascending, inplace=True)
return df.Lines.tolist()
sort_with_digits(s, ascending = True)
输出:
['3 s', '9 test', '12 nt', '345 eee']
注:如果您使用一个简单的
'\\n'.join(result)
列表(在result
),这将产生一个字符串格式类似于对输入(s
)。
result = sort_with_digits(s, ascending = True)
print('\n'.join(result))
输出:
12 nt
45 eee
45 gh
344 s
945 test
s = """
345 eee
1200 nt
9 test
-3 s
"""
# Expected Result: ['-3 s', '9 test', '345 eee', '1200 nt']
# And the solution produces this as well.
s = """
45 eee
12 nt
945 test
344 s
45 gh
"""
# Expected Result: ['12 nt', '45 eee', '45 gh', '344 s', '945 test']
# And the solution produces this as well.
好吧,这是一个糟糕的答案:
#!/usr/bin/python
import os
os.system('sort -n -r /path/to/file')
我使用 python 使用数字和反向选项运行 shell 命令“排序”。
我使用 python 是因为你标记了问题 python。
我使用了 -r 选项,因为您的输出示例似乎以相反的顺序排序。
如果它使用 subprocess 而不是 os.system (如其他答案所述),这将是一个更好的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.