首页 > 解决方案 > 如何使用文本文件中的数字在python中对文本文件进行排序

问题描述

我有以下文本文件:

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

解决方案


使用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')

推荐阅读