StyleInCode

RSS

 

Natural Sort

A solution for natural sorting. Post and solution inspired by Sorting for Humans.

Solution

""" natural_sort.py """

# usage: python3 natural_sort.py < list


import re
import sys


def text_nums(text):
    ''' list of chunks of text and whole numbers '''
    whole_num = r'([\d]+)'
    return [int(chunk) if chunk.isdecimal() else chunk.strip().lower()
            for chunk in re.split(whole_num, text)]


def natural_sort(values):
    ''' sort values in a natural way '''
    return sorted(values, key=text_nums)


if __name__ == '__main__':
    with sys.stdin as infile:
        textlines = infile.read().splitlines()

    for line in natural_sort(textlines):
        print(line)

permalink


Categories

Links