Package elisa :: Package extern :: Module natural_sort
[hide private]
[frames] | no frames]

Source Code for Module elisa.extern.natural_sort

 1  # -*- coding: utf-8 -*- 
 2  # From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/285264 
 3  # Licensed under PSF: http://python.org/license 
 4   
 5  import re 
 6  import copy 
 7   
 8   
9 -def try_int(s):
10 "Convert to integer if possible." 11 try: return int(s) 12 except: return s
13
14 -def natsort_key(s):
15 "Used internally to get a tuple by which s is sorted." 16 return map(try_int, re.findall(r'(\d+|\D+)', s))
17
18 -def natcmp(a, b):
19 "Natural string comparison, case sensitive." 20 return cmp(natsort_key(a), natsort_key(b))
21
22 -def natcasecmp(a, b):
23 "Natural string comparison, ignores case." 24 return natcmp(a.lower(), b.lower())
25
26 -def natsort(seq, cmp=natcmp):
27 "In-place natural string sort." 28 seq.sort(cmp)
29
30 -def natsorted(seq, cmp=natcmp):
31 "Returns a copy of seq, sorted by natural string sort." 32 temp = copy.copy(seq) 33 natsort(temp, cmp) 34 return temp
35
36 -def obj_natsorted(seq, cmp, key):
37 d = dict([(key(i), i) for i in seq]) 38 sorted = natsorted(d.keys(), cmp) 39 return [ d[k] for k in sorted ]
40