python - Turn a string into a valid filename? -
i have string want use filename, want remove characters wouldn't allowed in filenames, using python.
i'd rather strict otherwise, let's want retain letters, digits, , small set of other characters "_-.() "
. what's elegant solution?
the filename needs valid on multiple operating systems (windows, linux , mac os) - it's mp3 file in library song title filename, , shared , backed between 3 machines.
you can @ django framework how create "slug" arbitrary text. slug url- , filename- friendly.
their template/defaultfilters.py
(at around line 183) defines function, slugify
, that's gold standard kind of thing. essentially, code following.
def slugify(value): """ normalizes string, converts lowercase, removes non-alpha characters, , converts spaces hyphens. """ import unicodedata value = unicodedata.normalize('nfkd', value).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) value = unicode(re.sub('[-\s]+', '-', value))
there's more, left out, since doesn't address slugification, escaping.
Comments
Post a Comment