最近在优化项目的时候,要去除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)
Python glob与re模块实现文本批处理
在项目优化过程中,作者利用Python的glob和re模块,编写脚本批量替换Django models.py文件中Field的verbose_name注释,将'_(u"注释")'替换为'u"注释"',以此解决大规模项目的手动修改问题。"
100655979,7468389,逻辑斯蒂分布与回归模型解析,"['统计学', '机器学习', '数据挖掘', '回归分析', '概率论']
755

被折叠的 条评论
为什么被折叠?



