使用glob和re进行文本批量处理

在项目优化过程中,作者利用Python的glob和re模块,编写脚本批量替换Django models.py文件中Field的verbose_name注释,将'_(u"注释")'替换为'u"注释"',以此解决大规模项目的手动修改问题。" 100655979,7468389,逻辑斯蒂分布与回归模型解析,"['统计学', '机器学习', '数据挖掘', '回归分析', '概率论']
摘要由CSDN通过智能技术生成

        最近在优化项目的时候,要去除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)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值