python刪除指定路徑下文件的註釋(代碼)

由於工作中需要去掉某個路徑下的所有的代碼的註釋,但是呢用c實現太複雜就用python實現了一下,

正則表達式如果想看懂(https://blog.csdn.net/cao849861802/article/details/102505834

代碼如下:

import glob
import os
import re

#去掉註釋的正則表達式
rule = "(/\*\*/)|(/\*[\s\S]*?\*/)|(//[\s\S]*?\n)"

#去掉註釋/**/前面爲空格的表達式

#rule = "(/\*\*/)|(\*//\*)([ ]/\*[\s\S]*?\*/)|(//[\s\S]*?\n)"
file_type_list = ["h","c","cpp","H","C","CPP"]

def updatefile(path):
    print (path)
    fw = open(path,"r+");
    str = fw.read() ;
    #print("read content:" + str)
    fw.close();
    
    #replace comment
    str = re.sub(rule,"",str);
    #print ("change content:" + str);
    fw = open(path,"w");
    fw.write(str)
    
def listfiles(path,file_types):
    for file in os.listdir(path):
        listpath = path + "//" + file;
        if os.path.isdir(listpath):
            listfiles(listpath,file_types);
        elif os.path.isfile(listpath):
            splitlist = listpath.split('.')
            listLen = len(splitlist)
            prefx = splitlist[listLen - 1]
            if prefx in file_types:
                updatefile(listpath);

def deletComment(path, file_types):
    listfiles(path,file_types)
    
if __name__=='__main__':
    deletComment("F:/aaa",file_type_list);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章