简体   繁体   中英

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.

在此处输入图片说明

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.

在此处输入图片说明

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']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM