Replacer
ربما لديك مجموعة كبيرة من الملفات تحتاج القيام بتعديل سريع عليها جميعا ؟
فى هذه الجزئية سننشئ سكربت للتعديل على تلك الملفات بإستخدام
1- القواميس dict
2- ال recursion ( وهى استدعاء الدالة لنفسها)
حسنا هاهو السكربت
#!bin/python
#Imports#
import os
import os.path as op
import time
from sys import argv
class Replacer(object):
def __init__(self, parentDir, dic={}, exts=[]):
self.__parentDir=parentDir
self.__dic=dic
self.__exts=exts
self.__replacingTimes=0
def __getExt(self, s):
#idx=s.rfind(".")
#ext=s[idx:]
#return ext
return op.splitext(s)[1]
def replace(self):
start=self.__parentDir
for e in os.listdir(start): #foreach entry in os.listdir..
path=start+op.sep+e
if os.path.isfile(path):
ext=self.__getExt(path)
if not ext in self.__exts:
continue #Re-Loop..
#replace..
f=file(path, "r")
#Note: Not reading line by line as I've never met a more than 1MB text file!
src=f.read()
f.close()
for key in self.__dic:
self.__replacingTimes += src.count(key)
src=src.replace(key, self.__dic[key])
f=file(path, "w")
f.write(src)
f.close()
elif os.path.isdir(path):
#RECURSE..
rep=Replacer(path, self.__dic, self.__exts)
rep.replace()
else:
continue
الفكرة هى اعطاء مجلد لتعديل الملفات اللتى بداخله
وإذا كان داخله مجلد يتم فتح ذلك المجلد للتعديل على مافى داخله وهكذا
نبدأ ب
def __init__(self, parentDir, dic={}, exts=[]):
self.__parentDir=parentDir
self.__dic=dic
self.__exts=exts
self.__replacingTimes=0
تحديد مجلد الأب parentDir
تحديد الكلمات القديمة والجديدة فى قاموس ليتم استبدالهم
تحديد الإمتدادات القابل العمل عليها
الحصول على امتداد ملف
كما ذكرنا تستطيع استخدام os.path.splitext اللتى تعيد لنا قائمة مكونة من اسم الملف والإمتداد
def __getExt(self, s):
#idx=s.rfind(".")
#ext=s[idx:]
#return ext
return op.splitext(s)[1]
تستطيع ايضا كتابة ذلك يدويا بإستخدام الطريقة rfind للحصول على ترتيب ال نقطة ".” من اليمين -حتى لاتقع فى مشكلة مع ملفات مثل h1.ext1.ext2 – وتحسب الحروف من ذلك الترتيب الى النهاية
نأتى الى الطريقة replace
def replace(self):
start=self.__parentDir
for e in os.listdir(start): #foreach entry in os.listdir..
path=start+op.sep+e
if os.path.isfile(path):
ext=self.__getExt(path)
if not ext in self.__exts:
continue #Re-Loop..
#replace..
f=file(path, "r")
src=f.read()
f.close()
for key in self.__dic:
self.__replacingTimes += src.count(key)
src=src.replace(key, self.__dic[key])
f=file(path, "w")
f.write(src)
f.close()
elif os.path.isdir(path):
#RECURSE..
rep=Replacer(path, self.__dic, self.__exts)
rep.replace()
else:
continue
فى هذه الطريقة نعمل كالتالى
1- الحصول على قائمة بالمدخلات فى المجلد الرئيسى
for e in os.listdir(start): #foreach entry in os.listdir..
path=start+op.sep+e
2- اختبار ماإذا كان المسار ملفا
if os.path.isfile(path):
ext=self.__getExt(path)
3- اختبار اذا كان ذلك الملف يحوى امتداد مقبولا (محدد للإستبدال) وإلا نعود الى بداية الدوارة بإستخدام continue
if not ext in self.__exts:
continue #Loop..
5- اذا كان ملفا يحوى امتداد مقبول للإستبدال يتم فتحه لقراءة محتواه وغلقه واستبدال القيم القديمة بالجديدة
#replace..
f=file(path, "r")
src=f.read()
f.close()
for key in self.__dic:
self.__replacingTimes += src.count(key)
src=src.replace(key, self.__dic[key])
6- فتح الملف للكتابة وكتابة ذلك المحتوى مرة اخرى وغلقه
f=file(path, "w")
f.write(src)
f.close()
7- اذا كان المسار مجلدا فيتم فتحه (على اساس انه المجلد الرئيسى واعادة تنفيذ ماسبق بإستدعاء الطريقة replace وهذا مايسمى بال recursion
elif os.path.isdir(path):
#RECURSE..
rep=Replacer(path, self.__dic, self.__exts)
rep.replace()
else:
continue
التعامل مع المستخدم
def consoleMain():
##python replacer.py root [old] [new] [exts]
root, oldones, newones, exts=argv[1:5]
oldones=oldones.split(",") #use comma in between.
newones=newones.split(",") #use comma in between.
exts=exts.split(",") #use comma in between.
if len(oldones)==len(newones):
dic=dict(zip(oldones, newones))
#print "DIC:", dic
#print "EXTS:", exts
start=time.time()
rep=Replacer(root, dic, exts)
rep.replace()
end=time.time()
print "Time: ", (end-start)
else:
print "len(keys)!=len(values)"
exit(1)
start=time.time()
rep=Replacer(root, {old:new}, [exts])
rep.replace()
end=time.time()
print "Time: ", (end-start)
تابع لمزيد من التوضيح جزئية استخدام ال optparse