normalisename/normalisename.py

65 lines
2.4 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
2016-12-08 17:15:56 +00:00
from unidecode import unidecode
from os import rename
from os.path import basename, dirname
from os.path import join as joinpath
from argparse import ArgumentParser
from sys import exit
2016-12-08 17:15:56 +00:00
class normalisename:
@property
def separator(self):
return self._separator
@property
def whitelist(self):
return self._whitelist
def __init__(self, separator, whitelist):
self._separator = separator
self._whitelist = set(whitelist)
def normalise(self, files):
for path in files:
dir = dirname(path)
file = basename(path)
rename(path, joinpath(dir, self.normalname(file)))
def normalname(self, filename):
return unidecode(''.join(ch for ch in filename.replace(' ', self.separator)
if ch.isalnum()
or ch in self.whitelist))
if __name__ == '__main__':
# parse arguments
parser = ArgumentParser(description='Eliminate funky stuff from filenames.')
parser.add_argument('--separator', '-s', type=str, nargs='?', default='_',
help='Set separator to use (to replace spaces with).')
parser.add_argument('--allow', '-a', type=str, nargs='?', action='append',
help='Specify a special character to allow (it will not be removed).')
parser.add_argument('--disallow', '-d', type=str, nargs='?', action='append',
help='Specify a special character to disallow (it will removed).')
parser.add_argument('--whitelist', '-w', type=str,
help='Overwrite default whitelist (format: whitespace separated string).')
parser.add_argument('files', type=str, nargs='+',
help='File(s) to normalise the name of (relative or absolute path).')
args = parser.parse_args()
# verify arguments
if args.disallow:
if args.separator in args.disallow: exit('Disallowing your chosen separator makes no sense!')
# declare special characters that will not be removed (spaces are handled elsewhere)
whitelist = {' ', '.', '-'}
if args.whitelist: whitelist = set(args.whitelist.split())
# modify whitelist based on arguments
whitelist.add(args.separator)
if args.allow: whitelist = whitelist.union(set(args.allow))
if args.disallow: whitelist = whitelist.difference(set(args.disallow))
normalisename(args.separator, whitelist).normalise(args.files)