Python文件去除注释的方法
本文实例讲述了Python文件去除注释的方法。分享给大家供大家参考。具体实现方法如下:
#!/usr/bin/python
#-*-coding:GBK-*-
#writer:xmnathan
#py文件去注释
importre
importos
importConfigParser
Python='CleanNote'
defReadIni(path,section,option):#文件路径,章节,关键词
#读取ini
cf=ConfigParser.ConfigParser()
cf.read(path)
value=cf.get(section,option)#如果用getint()则直接读取该数据类型为整数
returnvalue
defIsPassLine(strLine):
#是否是可以忽略的行
#可忽略行的正则表达式列表
RegularExpressions=["""/'.*#.*/'""","""/".*#.*/"""",
"""/'/'/'.*#.*/'/'/'""","""/"/"/".*#.*/"/"/""""]
forOneinRegularExpressions:
zz=re.compile(One)
ifre.search(zz,strLine)==None:
continue
else:
returnTrue#有匹配则忽略
returnFalse
defReadFile(FileName):
#读取并处理文件
fobj=open(FileName,'r')
AllLines=fobj.readlines()
fobj.close()
NewStr=''
LogStr='/n%20s/n'%(FileName.split('//')[-1])#输出的日志
nline=0
foreachilineinAllLines:
index=eachline.find('#')#获取带注释句‘#'的位置索引
ifindex==-1ornline<3orIsPassLine(eachline):
ifeachiline.strip()!='':#排除纯空的行
NewStr=NewStr+eachiline
else:
ifindex!=0:
NewStr=NewStr+eachiline[:index]+'/n'#截取后面的注释部分
LogStr+="ChangeLine:%s/t%s"%(nline,eachline[index:])
nline+=1
returnNewStr,LogStr
defMakeCleanFile(SrcPath,DescPath,FileList):
fLog=open(DescPath+'//'+'CleanNoteLog.txt','w')
forFileinFileList:
curStr,LogStr=ReadFile(SrcPath+'//'+File)
fNew=open(DescPath+'//'+File,'w')
fNew=write(curStr)
fNew.close()
fLog.write(LogStr)
fLog.close()
defMain():
#从ini获取源文件夹及目标文件夹路径
IniPath=os.getcwd()+'//'+PtName+'.ini'
SrcPath=ReadIni(IniPath,PyName,'SrcPath')#源文件夹
DescPath=ReadIni(IniPath,PyName,'DescPath')#目的文件夹
#如果目的文件夹不存在,创建之
ifnotos.path.exists(DescPath):
os.makedirs(DescPath)
FileList=[]
forfilesinos.walk(SrcPath):
forFileNameinfiles[2]:
ifFileName.split('.')[-1]=='py':
FileList.append(FileName)
MakeCleanFile(SrcPath,DescPath,FileList)
if__name__=='__main__':
Main()
print'>>>End<<<'
os.system('pause')
ps:配置文件CleanNote.ini的格式
[CleanNote] SrcPath=E:/test DescPath=E:/test/newfiles
批量去除指定源文件夹中的py文件的注释,并生成拷贝与指定目的文件夹
希望本文所述对大家的Python程序设计有所帮助。