python一键取消注释_Python文件去除注释的方法
本文實(shí)例講述了Python文件去除注釋的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:
#!/usr/bin/python
# -*- coding: GBK -*-
#writer:xmnathan
#py文件去注釋
import re
import os
import ConfigParser
Python='CleanNote'
def ReadIni(path,section,option):#文件路徑,章節(jié),關(guān)鍵詞
#讀取ini
cf=ConfigParser.ConfigParser()
cf.read(path)
value=cf.get(section,option)#如果用getint()則直接讀取該數(shù)據(jù)類型為整數(shù)
return value
def IsPassLine(strLine):
#是否是可以忽略的行
#可忽略行的正則表達(dá)式列表
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獲取源文件夾及目標(biāo)文件夾路徑
IniPath=os.getcwd()+'//'+PtName+'.ini'
SrcPath=ReadIni(IniPath,PyName,'SrcPath')#源文件夾
DescPath=ReadIni(IniPath,PyName,'DescPath')#目的文件夾
#如果目的文件夾不存在,創(chuàng)建之
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<<
ps:配置文件CleanNote.ini的格式
[CleanNote]
SrcPath=E:/test
DescPath=E:/test/newfiles
批量去除指定源文件夾中的py文件的注釋,并生成拷貝與指定目的文件夾
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
本條技術(shù)文章來源于互聯(lián)網(wǎng),如果無意侵犯您的權(quán)益請(qǐng)點(diǎn)擊此處反饋版權(quán)投訴
本文系統(tǒng)來源:php中文網(wǎng)
總結(jié)
以上是生活随笔為你收集整理的python一键取消注释_Python文件去除注释的方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 描写开心激动的精彩句子243个
- 下一篇: 三下古诗三首之三衢道中诗句课堂笔记