python批量清除文件夹中的php文件代码注释及空行(转)
以下代码在win64位python3.7.6下运行良好,whitelist = ['php']指定需要在文件夹中需要批量操作的文件后缀名。本python代码修改后适用于php代码注释及空行(含tab行)的删除,如果清除其他类型的源码注释,需要修改相关代码。
另外本代码最原始的功能是用来统计文件中有效代码行数的,这里稍微做了修改,批量测了下5个php、html混合文件没有发现问题(在同一行有效代码后的 注释文件不会删除)
import os
import time
basedir = os.path.dirname(__file__)
filelists = []
# 指定想要统计的文件类型
whitelist = ['php']
#遍历文件, 递归遍历文件夹中的所有
def getFile(basedir):
global filelists
for 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 = 0
single_quotes_flag = False
double_quotes_flag = False
fname_new = fname+'.new.txt'
outfile = open(fname_new,'wb')
with open(fname, 'rb') as f:
for file_line in f:
file_line_old=file_line
file_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 += 1
print(fname + '----', count)
outfile.close()
# 单个文件行数
# print(fname,'----count:',count)
return count
if __name__ == '__main__' :
startTime = time.clock()
getFile(basedir)
totalline = 0
for 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,可以统计代码行数、注释行数、空格数。

基于互联网精神,在注明出处的前提下本站文章可自由转载!
本文链接:https://ranjuan.cn/python-delete-php-code-annotation/
赞赏
微信赞赏
支付宝赞赏
发表评论