有时候我在工作当中需要将代码中的注释去掉 下面我们就介绍一下吧
利用python去掉java中的注释
import com.example.pojo.MethodInfo; public class MethodInfoUtil{ private static boolean quoteFlag = false, lineStarFlag = false; private MethodInfoUtil() { } public static void main(String[] args) { String fileContent = readFileContent("C:\\Users\\tom\\Desktop\\User.java"); List<MethodInfo> methodInfos = MethodInfoUtil.getMethodInfo(fileContent); for (MethodInfo mi : methodInfos) { System.out.println(mi.getMethodBody()); System.out.println("========="); System.out.println("==={======"); } // System.out.println(fileContent); } public static List<MethodInfo> getMethodInfo(String fileContent) { // "public void test() "例如判断该字符串是否匹配正则。 String endWithMethodName = "[\\s\\S]*\\)\\W*"; // .java文件内容转为字符数组 List<MethodInfo> mis = new ArrayList<>(); // 得到方法名、参数类型、方法体,存放到集合中 char[] charArray = fileContent.toCharArray(); getBody2(charArray, fileContent, endWithMethodName,mis); return mis; } /** * 获取方法名、参数、方法体 * @param charArray * @param readFileContent * @param endWithMethodName */ public static void getBody2(char[] charArray,String readFileContent,String endWithMethodName,List<MethodInfo> mis) { String body = getBody(charArray);
def removeComments(s): i, n = 1, len(s) ans = '' while i < n: if s[i - 1] + s[i] == '//': i = s.find('\n', i) + 1 elif s[i - 1] + s[i] == '/*': i = s.find('*/', i + 1) + 3 else: ans += s[i - 1] i += 1 return filter(len, ans.split('\n'))
with open(r'E:\00004\MethodInfoUtil.java','r',encoding='utf-8') as f: ret = removeComments(f.read()) # print(ret) for i in ret: print(i)