[英]Sorting content of a .txt file in Python 3 line by line
I want to sort content of a .txt file that is read into Python from its highest to lowest numeric value.我想对读入 Python 的 .txt 文件的内容进行排序,从其最高到最低的数值。
Using the following code:使用以下代码:
with open("externalFile.txt", "r") as file:
content = file.read()
print(content)
list = content.splitlines()
def f(text):
return int(text) if text.isdigit() else text
def f1(text):
return [ func(z) for z in re.split('(\d+)', text) ]
list.sort(key=f1)
creates a list and within that list it sorts the content both alphabetically and numerically, as shown below.创建一个列表,并在该列表中按字母和数字对内容进行排序,如下所示。
However, I only want the content to be sorted numerically in Python, please see below.但是,我只希望在 Python 中按数字对内容进行排序,请参见下文。
How about this:这个怎么样:
def f1(text):
name, _, num = text.partition(':')
return int(num)
with open("sorting.txt", "r") as file:
l = file.read().splitlines()
l.sort(key=f1, reverse=True)
print(l)
If you only want to sort numerically, you can use list comprehension,如果只想按数字排序,可以使用列表理解,
with open("d:/data.txt") as file:
read_as_lit = [line.strip().split(":") for line in file]
sorted_file = sorted(read_as_lit, key=lambda y:int(y[1]), reverse=True)
print(sorted_file)
[['alpha', ' 50'], ['gamma', ' 45'], ['beta', ' 30'], ['alpha', ' 20'], ['gamma', ' 10'], ['alpha', ' 10']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.