[python]去除c++注释的脚本

时间:2023-01-17 00:07:19
   由于工作需要,我需要把c++代码里的注释去掉,所以写了这段小脚本。   
这里主要使用正则表达式查找 注释的内容,把它替换为空白。

匹配注释的正则表达式
    C_Rule = "(///*(/s|.)*?/*//)|(////.*)"

以下是代码:

  1. #--*-- coding: cp936 --*--
  2. import glob
  3. import os
  4. import re
  5. C_Rule = "(///*(/s|.)*?/*//)|(////.*)"
  6. file_type_list = ["h""c""cc""cpp""H""C""cc""CPP"]
  7. pS = re.compile(C_Rule) ;
  8. def updatefile(path):
  9.     ''''' 把文件读进内存里,用正则表达式查找
  10.     '''
  11.     print path ;
  12.     fw = open(path, "rw") ;
  13.     str = fw.read() ;
  14.     fw.close() ;
  15.     
  16.     #mS = pS.match(str) ;
  17.     #mS.
  18.     str = re.sub(C_Rule, "", str) ;
  19.     print  "connet : %s " % str ;
  20.     fw = open(path, "w") ;
  21.     fw.write(str)
  22. def listfiles(path, file_types):
  23.     '''''枚举path目录下的所有符合要求的文件
  24.     '''
  25.     for file in os.listdir(path):
  26.         listpath = path + "//"+file ;
  27.         if os.path.isdir(listpath):
  28.             listfiles(listpath, file_types);
  29.         elif os.path.isfile(listpath):
  30.             splitlist = listpath.split('.')
  31.             m = len(splitlist)
  32.             prefx = splitlist[m-1]
  33.             #print prefx
  34.             if prefx in file_types:
  35.                 updatefile(listpath) ;
  36.                 
  37. def remove_comment(path, file_types):
  38.     listfiles(path, file_types)
  39. if __name__ == '__main__':
  40.     path = "."
  41.     remove_comment(path, file_type_list) ;
  42.     #system("pause")