Created
August 30, 2020 21:46
-
-
Save jbosboom/e7d73eb06a356afb1d5d5ecbf00bf634 to your computer and use it in GitHub Desktop.
Approximate file renaming script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python2 | |
import sys, os, shutil, argparse, string, readline | |
from fuzzywuzzy import process | |
parser = argparse.ArgumentParser() | |
parser.add_argument('directory', type=str) | |
parser.add_argument('namelist', type=argparse.FileType(mode='r')) | |
# TODO: option to include extension in renaming? | |
args = parser.parse_args() | |
normal_characters = string.ascii_letters + string.digits | |
def normalize(s): | |
return s | |
ret = '' | |
for c in s: | |
if c in normal_characters: | |
ret += c | |
return ret | |
namelist = [x.strip() for x in args.namelist.readlines()] | |
normalized = {x: normalize(x) for x in namelist} | |
oldnames = list(os.listdir(args.directory)) | |
for old in oldnames: | |
if not os.path.isfile(os.path.join(args.directory, old)): | |
print old, "not a file?" | |
sys.exit(1) | |
mapping = {} | |
gave_up = [] | |
for old in oldnames: | |
normal = normalize(old.partition('.')[0]) | |
matches = process.extract(normal, normalized, limit=5) | |
print old | |
for m in matches: | |
answer = '?' | |
while answer not in ('y', 'Y', 'n', 'N'): | |
answer = raw_input('{} {} y/n? '.format(m[1], m[2])) | |
if answer in ('y', 'Y'): | |
mapping[old] = m[2] | |
break | |
else: | |
print 'Giving up' | |
gave_up.append(old) | |
inverse = {} | |
for g in gave_up: | |
print 'gave up:', g | |
for n in namelist: | |
if n not in mapping.itervalues(): | |
print 'unused: '+n | |
for k, v in mapping.iteritems(): | |
inverse.setdefault(v, []).append(k) | |
for k, v in inverse.iteritems(): | |
if len(v) > 1: | |
print 'clash: ', k, v | |
for q in v: | |
del mapping[q] | |
for k, v in mapping.iteritems(): | |
name, dot, ext = k.partition('.') | |
newname = v + dot + ext | |
shutil.move(os.path.join(args.directory, k), os.path.join(args.directory, newname)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment