473,473 Members | 2,151 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Natural string sorting

Summary:

Sorts strings in a way that seems natural to humans.
If the strings contain integers, then the integers are ordered
numerically. For example, sorts ['Team 11', 'Team 3', 'Team 1']
into the order ['Team 1', 'Team 3', 'Team 11'].

Code:

#---------------------------------------------------------
# natsort.py: Natural string sorting.
#---------------------------------------------------------

# By Seo Sanghyeon. Some changes by Connelly Barnes.

def try_int(s):
"Convert to integer if possible."
try: return int(s)
except: return s

def natsort_key(s):
"Used internally to get a tuple by which s is sorted."
import re
return map(try_int, re.findall(r'(\d+|\D+)', s))

def natcmp(a, b):
"Natural string comparison, case sensitive."
return cmp(natsort_key(a), natsort_key(b))

def natcasecmp(a, b):
"Natural string comparison, ignores case."
return natcmp(a.lower(), b.lower())

def natsort(seq, cmp=natcmp):
"In-place natural string sort."
seq.sort(cmp)

def natsorted(seq, cmp=natcmp):
"Returns a copy of seq, sorted by natural string sort."
import copy
temp = copy.copy(seq)
natsort(temp, cmp)
return temp

Examples:

You can use this code to sort tarball filenames:
natsorted(['ver-1.3.12', 'ver-1.3.3', 'ver-1.2.5', 'ver-1.2.15', 'ver-1.2.3', 'ver-1.2.1'])
['ver-1.2.1', 'ver-1.2.3', 'ver-1.2.5', 'ver-1.2.15', 'ver-1.3.3',
'ver-1.3.12']

Chemical elements:
natsorted(['C1H2', 'C1H4', 'C2H2', 'C2H6', 'C2N', 'C3H6']) ['C1H2', 'C1H4', 'C2H2', 'C2H6', 'C2N', 'C3H6']

Teams:
natsorted(['Team 101', 'Team 58', 'Team 30', 'Team 1']) ['Team 1', 'Team 30', 'Team 58', 'Team 101']

Pass natcasecmp as a second argument for case-insensitive sorting:
natsorted(['a5', 'A7', 'a15', 'a9', 'A8'], natcasecmp)

['a5', 'A7', 'A8', 'a9', 'a15']

Enjoy!
Jul 18 '05 #1
1 2399
Connelly Barnes wrote:
Summary:

[snip example code]

The Python Cookbook at http://aspn.activestate.com/ASPN/Python/Cookbook/
would be a much more effective way to make these snippets available
to others.
Jul 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: C. Barnes | last post by:
Summary: Sorts strings in a way that seems natural to humans. If the strings contain integers, then the integers are ordered numerically. For example, sorts into the order . Code:
3
by: Derek Basch | last post by:
Hello All, I need to sort a list using an unnatural sequence. I have a list like so: foo = print foo.sort()
13
by: Gram | last post by:
Hello, Can anyone help out with a bubble sort for strings using ASP? I have a text file of words id like to sort and count. Thanks in advance for any help. Gram.
3
by: John Smith | last post by:
Hello all: New problem. I am currently storing some mostly numeric values as ids in a db but with the possiblity that there are revisions to each. For instance say we have a record such as...
4
by: deancarstens | last post by:
Hi, This is a tougher one, but I'm quite sure someone will have a solution for this. Of course, a last minute thing thrown at me by my boss. I have a unique identifier consisting of regions,...
4
by: Jeoryos | last post by:
Well here is some code that will help explain the situation: I first make a struct that actually will be used to save some server informations: struct Server { public String IP; public int...
3
by: SneakyElf | last post by:
i am very green with c++ so i get stuck on very simple things anyway, i need to write a program that would read data from file (containing names of tv shows and their networks) one line at a time...
7
by: pt36 | last post by:
Hi I have a php string like this: $string = "one two three four five" I have to sorting the values randomly every time the page are loaded. So, for example: first time "one two three four five"...
26
by: Brad | last post by:
I'm writing a function to remove certain characters from strings. For example, I often get strings with commas... they look like this: "12,384" I'd like to take that string, remove the comma...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.