最近在优化项目的时候,要去除Django的国际化,需要将每个models.py中每个Field里的 'verbose_name=_(u"注释")' 替换为 'verbose_name=u"注释"。由于项目规模很大,手动改起来实在是麻烦,所以写个简单脚本来进行批量处理。
代码如下:
#-*-coding:utf8-*-
import os,re,glob
def glob_files(re_file):
"""获取指定路径下符合要求的文件"""
files = glob.glob(re_file)
return files
def file_match(pattern, file):
"""获取指定文件匹配"""
def search_match(pattern, text):
"""获取文本中所有的匹配"""
return [match for match in re.findall(pattern, text)]
#读取文件,替换匹配
with open(file, 'r+') as f:
text = f.read()
matches = search_match(pattern, text)
print '------------{0}------------'.format(file)
for match in matches:
print match[0],match[1]
text = text.replace(match[0], match[1])
print ''
#TODO:seek后,write乱码
#f.seek(0)
with open(file, 'w') as f:
f.write(text)
if __name__ == '__main__':
#file_match(r'verbose_name\s*=\s*(_\((.*?)\))','test.py')
os.chdir('/home/wuhailei/works/com')
files = glob_files('*/models.py')
map(lambda x: file_match(r'verbose_name\s*=\s*(_\((.*?)\))', x), files)