python - 如何使用文本文件中的数字在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并且没有系统调用:
# 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')
推荐阅读
- azure - 写入 Azure Blob 存储。一切看起来都很好,但它会创建很多临时文件
- python - 创建绘图的 Pytest 测试函数
- javascript - 在搜索结果中包含图像的 Javascript 代码
- c - 为什么标准规定 C 中结构、枚举和联合的标记存在三种可能的命名空间,而实际上它们只有一种?
- json - 使用杰克逊子类型时如何避免获得带有随机信息的额外字段?
- postgresql - docker compose ignoring env vars when creating the container for postgres
- mysql - 如何使用 node-red 从数据库中提取数据
- node.js - 在设置关联时定义要加入的列
- java - Android Paho Mqtt - close() 与 unregisterResources() - OutOfMemoryError
- c# - 如何在 C# 中创建列表变量?