Skip to content

Commit

Permalink
Merge pull request #9 from imcf/better-sort
Browse files Browse the repository at this point in the history
Add function for better sorting and use it
  • Loading branch information
ehrenfeu authored Apr 28, 2023
2 parents 3a1d930 + b573d8b commit 90cc99c
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 4 deletions.
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,18 @@

<!-- markdownlint-disable MD024 (no-duplicate-header) -->

## 1.4.0

### Added

* `imcflibs.strtools.sort_alphanumerically` to sort a list of strings taking
into account numerical values correctly.

### Changed

* `imcflibs.pathtools.listdir_matching` is now using the new
`sort_alphanumerically()` function from above.

## 1.3.0

### Added
Expand Down
9 changes: 5 additions & 4 deletions src/imcflibs/pathtools.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
"""Helper functions to work with filenames, directories etc."""

import os.path
import platform
from os import sep
import os.path

from . import strtools
from .log import LOG as log


Expand Down Expand Up @@ -169,8 +170,8 @@ def listdir_matching(path, suffix, fullpath=False, sort=False):
paths to the matching files (the default is False, which will result in
the file names only, without path).
sort : bool, optional
If set to True, the returned list will be sorted using Python's built-in
`sorted()` call. By default False.
If set to True, the returned list will be sorted using
`imcflibs.strtools.sort_alphanumerically()`.
Returns
-------
Expand All @@ -187,7 +188,7 @@ def listdir_matching(path, suffix, fullpath=False, sort=False):
matching_files.append(candidate)

if sort:
matching_files = sorted(matching_files)
matching_files = strtools.sort_alphanumerically(matching_files)

return matching_files

Expand Down
28 changes: 28 additions & 0 deletions src/imcflibs/strtools.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""String related helper functions."""

import re


# this is taken from numpy's iotools:
def _is_string_like(obj):
Expand Down Expand Up @@ -109,3 +111,29 @@ def strip_prefix(string, prefix):
if string.startswith(prefix):
string = string[len(prefix) :]
return string


def sort_alphanumerically(data):
"""Sort a list alphanumerically.
Parameters
----------
data : list
List containing all the files to sort.
Returns
-------
list
List with filenames sorted.
Examples
--------
>>> sorted([ "foo-1", "foo-2", "foo-10" ])
["foo-1", "foo-10", "foo-2"]
>>> sort_alphanumerically([ "foo-1", "foo-2", "foo-10" ])
["foo-1", "foo-2", "foo-10"]
"""
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [convert(c) for c in re.split("([0-9]+)", key)]
return sorted(data, key=alphanum_key)

0 comments on commit 90cc99c

Please sign in to comment.