以下代码在win64位python3.7.6下运行良好,whitelist = [‘php’]指定需要在文件夹中需要批量操作的文件后缀名。本python代码修改后适用于php代码注释及空行(含tab行)的删除,如果清除其他类型的源码注释,需要修改相关代码。
另外本代码最原始的功能是用来统计文件中有效代码行数的,这里稍微做了修改,批量测了下5个php、html混合文件没有发现问题(在同一行有效代码后的 注释文件不会删除)
import osimport timebasedir = os.path.dirname(__file__)filelists = []# 指定想要统计的文件类型whitelist = ['php']#遍历文件, 递归遍历文件夹中的所有def getFile(basedir):global filelistsfor parent,dirnames,filenames in os.walk(basedir):#for dirname in dirnames:# getFile(os.path.join(parent,dirname)) #递归for filename in filenames:ext = filename.split('.')[-1]#只统计指定的文件类型,略过一些log和cache文件if ext in whitelist:filelists.append(os.path.join(parent,filename))#统计一个文件的行数def countLine(fname):count = 0single_quotes_flag = Falsedouble_quotes_flag = Falsefname_new = fname+'.new.txt'outfile = open(fname_new,'wb')with open(fname, 'rb') as f:for file_line in f:file_line_old=file_linefile_line = file_line.strip()# print(file_line)# 空行if file_line == b'':pass# 注释 # 开头elif file_line.startswith(b'#'):pass# 注释 // 开头elif file_line.startswith(b'//'):pass# 注释/* */在同一行开头结尾的情况elif file_line.startswith(b"/*") and file_line.endswith(b"*/"):single_quotes_flag = False# 注释 单引号 ''' 开头---/*elif file_line.startswith(b"/*") and not single_quotes_flag:single_quotes_flag = True# 注释 中间 和 ''' 结尾---- */elif single_quotes_flag == True:if file_line.endswith(b"*/"):single_quotes_flag = False# 注释 双引号 """ 开头#elif file_line.startswith(b'"""') and not double_quotes_flag:# double_quotes_flag = True# 注释 中间 和 """ 结尾#elif double_quotes_flag == True:# if (file_line.endswith(b'"""')):# double_quotes_flag = False# 代码else:#outfile.write(file_line_old+b'\n')#str=file_line.strip().replace(b' ', b'').replace(b'\n', b'').replace(b'\t', b'').replace(b'\r', b'').strip()#if (not str2.startswith(b'//') and str2!="\n"):outfile.write(file_line_old)count += 1print(fname + '----', count)outfile.close()# 单个文件行数# print(fname,'----count:',count)return countif __name__ == '__main__' :startTime = time.clock()getFile(basedir)totalline = 0for filelist in filelists:totalline = totalline + countLine(filelist)print('\033[43m total lines: \033[0m'.center(20,'-'),totalline)print('Done! Cost Time: %0.5f second' % (time.clock() - startTime))
因为最近有申请软著的打算,所以需要一个批量清除注释的东西,找了很久才发现上面这个代码改改还是很好用的。另外如果想要统计代码行数的话可以试试这个软件——SourceCounter,可以统计代码行数、注释行数、空格数。

发表评论