本文实例讲述了Python删除Java源文件中全部注释的实现方法。分享给大家供大家参考,具体如下:
同事想删除一个Java项目中的全部注释,让我帮忙想想办法。
没找不到合适工具,就写了这个脚本,遍历指定目录,查找*.java文件,删除其中/* */之间,及// 至行末的内容。
(用之前要改改其中的路径):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
#!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程序设计有所帮助。
原文链接:http://blog.csdn.net/codearhat/article/details/6852483