Skip to content

Use natsort.os_sorted to sort files in the browser - #990

Merged
wkentaro merged 1 commit into
mainfrom
feature/natsort
Feb 26, 2022
Merged

wkentaro merged 1 commit into
mainfrom
feature/natsort

Conversation

@wkentaro

Copy link
Copy Markdown
Owner

Close #955
Close #989
Close #953

It seems there're many needs for sorting files naturally in the file browser.
With a bit of research, I have decided to use natsort.os_sorted, since it is at least to me the most "natural" if files are sorted as the same way as the file manager of an OS (I use Finder on macOS).

Below is an example of the result:

import re
import natsort

filenames = [
    "img_1.jpg",
    "img_100.jpg",
    "img_10.jpg",
    "img_11.jpg",
    "img_1-1.jpg",
    "img_12-1.jpg",
]

print("original  :", filenames)
print(
    "re.sub(\D):",
    sorted(filenames, key=lambda x: int(re.sub("\D", "", x.lower()))),
)
print("natsorted :", natsort.natsorted(filenames))
print("os_sorted :", natsort.os_sorted(filenames))

print()

filenames = [
    "image1.png",
    "image10.png",
    "image2.png",
    "image200.png",
    "image3.png",
]
print("original  :", filenames)
print(
    "re.sub(\D):",
    sorted(filenames, key=lambda x: int(re.sub("\D", "", x.lower()))),
)
print("natsorted :", natsort.natsorted(filenames))
print("os_sorted :", natsort.os_sorted(filenames))
original  : ['img_1.jpg', 'img_100.jpg', 'img_10.jpg', 'img_11.jpg', 'img_1-1.jpg', 'img_12-1.jpg']
re.sub(\D): ['img_1.jpg', 'img_10.jpg', 'img_11.jpg', 'img_1-1.jpg', 'img_100.jpg', 'img_12-1.jpg']
natsorted : ['img_1-1.jpg', 'img_1.jpg', 'img_10.jpg', 'img_11.jpg', 'img_12-1.jpg', 'img_100.jpg']
os_sorted : ['img_1.jpg', 'img_1-1.jpg', 'img_10.jpg', 'img_11.jpg', 'img_12-1.jpg', 'img_100.jpg']

original  : ['image1.png', 'image10.png', 'image2.png', 'image200.png', 'image3.png']
re.sub(\D): ['image1.png', 'image2.png', 'image3.png', 'image10.png', 'image200.png']
natsorted : ['image1.png', 'image2.png', 'image3.png', 'image10.png', 'image200.png']
os_sorted : ['image1.png', 'image2.png', 'image3.png', 'image10.png', 'image200.png']

@wkentaro wkentaro self-assigned this Feb 25, 2022
@wkentaro
wkentaro merged commit 4d4cd20 into main Feb 26, 2022
@wkentaro
wkentaro deleted the feature/natsort branch February 26, 2022 14:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

why labelme can't next images as in a sorted sequence as like in folder?

1 participant