python

超轻量级php框架startmvc

Python删除Java源文件中全部注释的实现方法

更新时间:2020-05-06 15:06:01 作者:startmvc
本文实例讲述了Python删除Java源文件中全部注释的实现方法。分享给大家供大家参考,具体

本文实例讲述了Python删除Java源文件中全部注释的实现方法。分享给大家供大家参考,具体如下:

同事想删除一个Java项目中的全部注释,让我帮忙想想办法。

没找不到合适工具,就写了这个脚本,遍历指定目录,查找*.java文件,删除其中/* */之间,及// 至行末的内容。

(用之前要改改其中的路径):


#!D:\Python32
# 过滤JAVA程序中的注释
# 如果字符串中有注释符号的话会有问题。
import os
import re
import io
# 改这个目录!!!
top_dir = "E:\\java_comments_trim\\";
# 状态
S_INIT = 0;
S_SLASH = 1;
S_BLOCK_COMMENT = 2;
S_BLOCK_COMMENT_DOT = 3;
S_LINE_COMMENT = 4;
S_STR = 5;
S_STR_ESCAPE = 6;
def trim_dir(path):
 print("目录:" + path);
 for root, dirs, files in os.walk(path):
 for name in files:
 trim_file(os.path.join(root, name))
 #for name in dirs:
 #trim_dir(os.path.join(root, name))
def trim_file(path):
 print("文件:" + path);
 if re.match(".*java{1}quot;, path):
 print(" 处理");
 else:
 print(" 忽略");
 return;
 bak_file = path + ".bak";
 os.rename(path, bak_file);
 fp_src = open(bak_file);
 fp_dst = open(path, 'w');
 state = S_INIT;
 for line in fp_src.readlines():
 for c in line:
 if state == S_INIT:
 if c == '/':
 state = S_SLASH;
 elif c == '"''"':
 state = S_STR;
 fp_dst.write(c);
 else:
 fp_dst.write(c);
 elif state == S_SLASH:
 if c == '*':
 state = S_BLOCK_COMMENT;
 elif c == '/':
 state = S_LINE_COMMENT;
 else:
 fp_dst.write('/');
 fp_dst.write(c);
 elif state == S_BLOCK_COMMENT:
 if c == '*':
 state = S_BLOCK_COMMENT_DOT;
 elif state == S_BLOCK_COMMENT_DOT:
 if c == '/':
 state = S_INIT;
 else:
 state = S_BLOCK_COMMENT;
 elif state == S_LINE_COMMENT:
 if c == '\n':
 state = S_INIT;
 elif state == S_STR:
 if c == '\\':
 state = S_STR_ESCAPE;
 elif c == '"':
 state = S_INIT;
 fp_dst.write(c);
 elif state == S_STR_ESCAPE:
 # 这里未完全实现全部序列,如\oNNN \xHH \u1234 \U12345678,但没影响
 state = S_STR;
 fp_dst.write(c);
 fp_src.close();
 fp_dst.close();
trim_dir(top_dir);

Python 删除 Java源文件 注释