Странно, у меня спойлер работает ОК
На всякий случай добавляю как вложение, переименовать в .py
Ну, по просьбам трудящихся выкладываю эту простыню, заранее извиняюсь:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# renamer.py
#
# Copyright 2010 serge <serge@serge-desktop>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
import os, sys, string, re, codecs
fromdir='/media/G/VC/5'
name=''
extension=''
encodings=['ansi','ascii','UTF-8', 'cp1251', 'koi-8r']
dict_eng_rus={'a':'а','b':'б','v':'в','g':'г','d':'д','e':'е','zh':'ж','z':'з','i':'и','k':'к','l':'л','m':'м','n':'н','o':'о','p':'п','r':'р','s':'с','t':'т','u':'у','f':'ф','h':'х','c':'ц','ch':'ч','sh':'ш','sch':'щ','w':'щ','iy':'ы','\'':'ь','ju':'ю','ja':'я','A':'А','B':'Б','V':'В','G':'Г','D':'Д','E':'Е','Zh':'Ж','Z':'З','I':'И','K':'К','L':'Л','M':'М','N':'Н','O':'О','P':'П','R':'Р','S':'С','T':'Т','U':'У','F':'Ф','H':'Х','C':'Ц','Ch':'Ч','Sh':'Ш','Sch':'Щ','Iy':'Ы','Ju':'Ю','Ja':'Я'}
diftong_eng_rus={'zh':'ж','ch':'ч','sh':'ш','sch':'щ','je':'е','jo':'ё','yo':'ё','yu':'ю','ya':'я','ju':'ю','ja':'я','Io':'Ё','Ch':'Ч','Sh':'Ш','Sch':'Щ','W':'Щ','Yu':'Ю','Ya':'Я','Ju':'Ю','Ja':'Я'}
ycukeng_eng_rus={'j':'й','y':'ы'}
iy_eng_rus={'iy':'ый','yj':'ый'}
def translit(filenames, encodings):
i=0
extension=''
print 'Transliteration:'
for files in filenames:
name=filenames[i]
oldname=name
#testname=os.path.isfile(name); print name, testname
print '+',
#if os.path.isfile(name):
name, extension=os.path.splitext(name)
#print name, extension
for items in diftong_eng_rus:
try:
name=string.replace(name, items, diftong_eng_rus[items])
except:
pass
for items in iy_eng_rus:
try:
name=string.replace(name, items, iy_eng_rus[items])
except:
pass
for items in ycukeng_eng_rus:
try:
name=string.replace(name, items, ycukeng_eng_rus[items])
except:
pass
for items in dict_eng_rus:
name=string.replace(name, items, dict_eng_rus[items])
name=name+extension
oldname=os.path.join(fromdir, oldname); name=os.path.join(fromdir, name)
os.rename(oldname, name)
#print oldname
#print name
i=i+1
print '\n'
print i, 'files transliterated'
def getopts(argv):
opts={}
i=0
j=i+1
for i in range(len(argv)):
if argv[i][0]=='-' and argv[j][0]!='-':
opts[argv[i]]=argv[j]
i=i+2
else:
opts[argv[i]]=argv[i]
i=i+1
j=i+1
if j>len(argv)-1:
j=len(argv)-1
return opts
def dir_list(fromdir):
filenames=os.listdir(fromdir)
filenames.sort()
return filenames
def split_name(filenames):
i=0
while i < len(filenames):
name=filenames[i]
name=unicode(name, 'UTF-8')
if os.path.isfile(name):
name, extension=os.path.splitext(name)
break
i=i+1
return name, extension
def learn(name, dictname):
dictionary={}
template_name=string.splitfields(name,'.')
dictname=os.path.join(fromdir, dictname)
for item in template_name:
print 'Задайте значение для замены', item
dictionary[item]=unicode(raw_input('? '), 'UTF-8')
file=codecs.open(dictname, mode='w', encoding='UTF-8', errors='strict', buffering=1)
for item in dictionary:
stroke=item+':'+dictionary[item]+'\n'
file.write(stroke)
file.close()
return dictionary
def read_dict(dictname, encodings):
dictionary={}
file=open(dictname, 'r')
for line in file.readlines():
for enc in encodings:
try:
line=unicode(line, enc)
except:
pass
line=string.replace(line, '\n', '')
key, item=string.splitfields(line,':')
dictionary[key]=item
file.close()
return dictionary
def print_dict2(name):
template_name=string.splitfields(name,'.')
dictname=os.path.join(fromdir, 'dict.txt')
j=0
file=open(dictname, 'w')
while j < len(template_name):
str=template_name[j]+':'+'\n'
print str
j=j+1
file.write(str)
file.close()
return dictname
def create_dir(todir):
if os.path.exists(todir):
print 'Directory exist'
else:
try:
os.mkdir(todir)
except OSError: print "Probably access denied"
def maxnum(filenames, num):
num=re.compile(num)
maxnum=0
leadzero=''
for files in filenames:
name=files
for j in num.findall(name):
curnum=int(j[1:])
if curnum > maxnum:
maxnum=curnum
countzero=len(str(maxnum))
return countzero
def namefilter(filenames, filter):
filter=re.compile(filter)
#repl=re.compile('\d\d\d\d')
i=0
matches=0
print 'Name filter:'
for files in filenames:
name=filenames[i]
oldname=name
print '+',
if os.path.isfile(name):
name, extension=os.path.splitext(name)
name=string.replace(name, '.', ' ')
name,matches=re.subn(filter, '', name)
name=name+extension
for j in range(len(name)):
name=string.replace(name, ' ', ' ')
j=j+1
name=string.replace(name, ' .', '.')
#os.rename(oldname, name)
print oldname
print name, matches
i=i+1
print '\n'
print i, 'files filtered'
def renamer(filenames, dictionary, num, encodings):
print 'Renamer:',
i=0
extension=''
num=re.compile(num)
countzero=maxnum(filenames, num)
leadzero='0='+str(countzero)
for files in filenames:
name=filenames[i]
print '+',
for j in num.findall(name):
repl=j[1:]
repl=format(int(repl), leadzero)
for enc in encodings:
try:
name=unicode(name, enc)
except:
pass
oldname=name
if os.path.isfile(name):
name, extension=os.path.splitext(name)
for items in dictionary:
name=string.replace(name, '.', ' ')
name=string.replace(name, items, dictionary[items])
name=string.replace(name, ' ', ' ')
name=re.sub(num, repl, name)
name=name+extension
name=string.replace(name, ' .', '.')
#os.rename(oldname, name)
print oldname, name
i=i+1
def main():
from sys import argv
myargs=getopts(argv)
filter='\d\d\d\d\s.+'
num='\(\d+'
dictname='./dict.txt'
if myargs.has_key('-h'):
print 'Usage: ~/<path>/<to>/renamer5.py -f -t -r dict.txt'
print '-h этот текст'
print '-f обрезать все символы имени, начиная с года'
print '-t транслитерировать имена англ --> рус'
print '-f должна быть в списке аргументов раньше, чем -t'
print 'Опции для сериалов (имена различаются только цифрами)'
print '(файлы сериалов лучше обрабатывать отдельно)'
print '-l dict2.txt обучение программы на первом файле с записью словаря в dict2.txt'
print '-p записать заготовку словаря в файл (по умолч - dict.txt) для редактирования'
print '-r dict2.txt переименовать сериал, используя словарь dict2.txt'
#create_dir('renamed')
filenames=dir_list(fromdir)
#print filenames
if myargs.has_key('-l'):
dictname=myargs['-l']
name, extension=split_name(filenames)
dictionary=learn(name, dictname)
if myargs.has_key('-p'):
dictname=print_dict2(name)
if myargs.has_key('-f'):
#filenames=dir_list(fromdir)
namefilter(filenames, filter)
if myargs.has_key('-t'):
#filenames=dir_list(fromdir)
translit(filenames, encodings)
if myargs.has_key('-r'):
keyname=myargs['-r']
if keyname!='-r':
dictname=myargs['-r']
#print dictname
dictionary=read_dict(dictname, encodings)
#filenames=dir_list(fromdir)
renamer(filenames, dictionary, num, encodings)
return 0
if __name__ == '__main__':
main()