Python文件去除注释的方法
更新时间:2015年05月25日 12:33:06 作者:惟愿莲心不染尘
这篇文章主要介绍了Python文件去除注释的方法,涉及Python正则表达式及文件操作的相关技巧,需要的朋友可以参考下
本文实例讲述了Python文件去除注释的方法。分享给大家供大家参考。具体实现方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | #!/usr/bin/python # -*- coding: GBK -*- #writer:xmnathan #py文件去注释 import re import os import ConfigParser Python = 'CleanNote' def ReadIni(path,section,option): #文件路径,章节,关键词 #读取ini cf = ConfigParser.ConfigParser() cf.read(path) value = cf.get(section,option) #如果用getint()则直接读取该数据类型为整数 return value def IsPassLine(strLine): #是否是可以忽略的行 #可忽略行的正则表达式列表 RegularExpressions = [ """/'.*#.*/'""" , """/".*#.*/""" ", """/'/'/'.*#.*/'/'/'""" , """/"/"/".*#.*/"/"/""" "] for One in RegularExpressions: zz = re. compile (One) if re.search(zz,strLine) = = None : continue else : return True #有匹配 则忽略 return False def ReadFile(FileName): #读取并处理文件 fobj = open (FileName, 'r' ) AllLines = fobj.readlines() fobj.close() NewStr = '' LogStr = '/n%20s/n' % (FileName.split( '//' )[ - 1 ]) #输出的日志 nline = 0 for eachiline in AllLines: index = eachline.find( '#' )#获取带注释句‘#'的位置索引 if index = = - 1 or nline< 3 or IsPassLine(eachline): if eachiline.strip()! = '': #排除纯空的行 NewStr = NewStr + eachiline else : if index! = 0 : NewStr = NewStr + eachiline[:index] + '/n' #截取后面的注释部分 LogStr + = "ChangeLine: %s/t%s" % (nline,eachline[index:]) nline + = 1 return NewStr,LogStr def MakeCleanFile(SrcPath,DescPath,FileList): fLog = open (DescPath + '//' + 'CleanNoteLog.txt' , 'w' ) for File in FileList: curStr,LogStr = ReadFile(SrcPath + '//' + File ) fNew = open (DescPath + '//' + File , 'w' ) fNew = write(curStr) fNew.close() fLog.write(LogStr) fLog.close() def Main(): #从ini获取源文件夹及目标文件夹路径 IniPath = os.getcwd() + '//' + PtName + '.ini' SrcPath = ReadIni(IniPath,PyName, 'SrcPath' ) #源文件夹 DescPath = ReadIni(IniPath,PyName, 'DescPath' ) #目的文件夹 #如果目的文件夹不存在,创建之 if not os.path.exists(DescPath): os.makedirs(DescPath) FileList = [] for files in os.walk(SrcPath): for FileName in files[ 2 ]: if FileName.split( '.' )[ - 1 ] = = 'py' : FileList.append(FileName) MakeCleanFile(SrcPath,DescPath,FileList) if __name__ = = '__main__' : Main() print '>>>End<<<' os.system( 'pause' ) |
ps:配置文件CleanNote.ini的格式
批量去除指定源文件夹中的py文件的注释,并生成拷贝与指定目的文件夹
希望本文所述对大家的Python程序设计有所帮助。

微信公众号搜索 “ 脚本之家 ” ,选择关注
程序猿的那些事、送书等活动等着你
相关文章
在Python中使用Protocol Buffers的详细介绍
本文详细介绍了协议缓冲区(Protocol Buffers)在Python中的应用,包括其定义、序列化和解析过程,协议缓冲区是一种灵活且高效的自动化解决方案,本文包括了如何将地址簿应用程序的个人详细信息写入文件的示例代码,并提供了相应的下载和安装指导,感兴趣的朋友一起看看吧2024-10-10使用python图形模块turtle库绘制樱花、玫瑰、圣诞树代码实例
这篇文章主要介绍了用python绘制樱花、玫瑰、圣诞树代码实例,需要的朋友可以参考下2020-03-03
最新评论