Python如何腳本過濾文件中的注釋
確保對模塊, 函數, 方法和行內注釋使用正確的風格,Python中的注釋有單行注釋和多行注釋。如果希望去除文件中所有注釋,如何做呢?
Python中的注釋:
Python中單行注釋以 # 開頭,例如:
# 這是一個注釋print('Hello, World!')
多行注釋用三個單引號 ’’’ 或者三個雙引號 ''' 將注釋括起來,例如:
#!/usr/bin/python3 ’’’這是多行注釋,用三個單引號這是多行注釋,用三個單引號 這是多行注釋,用三個單引號’’’print('Hello, World!')
使用Python腳本快速去除文件中的注釋:
#!/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 Falsedef 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 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的格式
[CleanNote] SrcPath=E:/test DescPath=E:/test/newfiles
批量去除指定源文件夾中的py文件的注釋,并生成拷貝與指定目的文件夾
實例擴展:
print('程序中常見的注釋') 注意:此程序將會刪除的,會在Demo注釋末尾添加 YES,不會刪除的 NO # 這是第一種注釋,’#’放在開頭(YES) ret = analysix(data) # 這是第二種注釋,’#’跟在某一個語句后面(NO) '''第三種注釋有時候需要注釋掉某一整塊東西的時候,使用這個(YES)''' ''' 第四種注釋,這是函數或者類的說明(NO)''' # 這是第四種注釋,’#’前面加了空格(YES)
到此這篇關于Python如何腳本過濾文件中的注釋的文章就介紹到這了,更多相關Python腳本過濾文件中的注釋方法內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
