程序员Python 运维Python语言与信息数据获取和机器学习

Python实现的一个代码分析功能

2017-09-07  本文已影响211人  LasseYang
主要实现的功能:
  1.单页、总行数代码统计
  2.单页、总行数注释统计
  3.代码注释率、总注释率统计
  4.根据注释率/注释行数/代码行数进行排序
  5.根据注释方式 “//”   “<!---->”  “#”   “/***/” 进行注释分析  -> 暂时只有这些
1,遍历文件夹
    # 开始
    traverse_files(root)
    print("总行数", code_num, '注释行数', code_annotation_num, '注释比例',
          str(int(round(code_annotation_num / code_num, 2) * 100)) + "%")
    print("===================")
    print("===================")
    print("===================")
    print("===================")
    print("===================")
    # print(error_file_lst)
    for item in file_list:
        print(item[0],
              "文件行数:%s" % item[1][0],
              "注释行数:%s" % item[1][1],
              "注释比例:%s" % item[1][2]
              )

traverse_files是一个递归函数,像这样,过滤文件后缀以及循环文件夹。

    for i in os.listdir(path):
        file_path = os.path.join(path, i)
        if os.path.isfile(file_path):
            if len(need_suffix) != 0:
                for suffix in need_suffix:
                    if suffix in file_path:
                        print_line(file_path)
            else:
                print_line(file_path)

        else:
            traverse_files(os.path.join(path, i))
2,读取文件
    try:
        with open(root_path, 'r', encoding=encoding) as lineFile:
            block_list = lineFile.readlines()
            # 已经被/****/以及<!--   -->注释的 里面的所有数据不在算做注释行
            annotation_line_lst = []
            # 读取每一行 放到集合中
            if len(annotation_list) > 0:
                annotation_line = 0

                for index, block_line in enumerate(block_list):
                    block_line = block_line.replace('\t', '').replace('\n', '').replace(' ', '')
                    try:
                        is_reset_loop = False
                        for tuple_line in annotation_line_lst:
                            if index in tuple_line:
                                is_reset_loop = True
                                break
                        if is_reset_loop:
                            continue

                        # Python
                        if dl.Python in annotation_list:
                            if block_line.find("#") != -1:
                                annotation_line += 1

                        # 通用 java  还有 html 都有这样的注释
                        if dl.Java in annotation_list \                           
                                or dl.HTML in annotation_list:
                            if block_line[0:4] == '<!--':
                                for i, line in enumerate(block_list[index:]):
                                    line = line.replace('\t', '').replace('\n', '').replace(' ', '')
                                    # 判断 --> 是否是本行的最后一行
                                    if "-->" in line and '-->' == line[-3:]:
                                        annotation_line_temp = i + 1
                                        annotation_line += annotation_line_temp
                                        annotation_line_lst.append(range(index, index + annotation_line_temp))
                                        break

                        if dl.Java in annotation_list:
                            if block_line[0] == '/' and block_line[1] == '/':
                                annotation_line += 1
                            if block_line[0] == '/' and block_line[1] == '*':
                                for i, line in enumerate(block_list[index:]):
                                    line = line.replace('\t', '').replace('\n', '').replace(' ', '')
                                    if "*/" in line and "*/" == line[-2:]:
                                        annotation_line_temp = i + 1
                                        annotation_line += annotation_line_temp
                                        annotation_line_lst.append(range(index, index + annotation_line_temp))
                                        break

                    except Exception as e:
                        pass
            if is_fliter_none_line:
                block_list_copy = []
                for item in block_list:
                    if item.split():
                        block_list_copy.append(item)
                block_list = block_list_copy
            # 将单个文件的信息保存起来
            print_message(root_path.split(os.sep)[-2:], numline=len(block_list), annotation_line=annotation_line)
            global code_num
            code_num += len(block_list)
    except UnicodeDecodeError as e:
        error_file_lst.append(root_path)
        pass
3,统计
def print_message(filename, **kwargs):
    line_num = kwargs["numline"]
    annotation_num = kwargs['annotation_line']
    global code_annotation_num
    code_annotation_num += annotation_num
    annotation_proportion = str(int(round(annotation_num / line_num, 2) * 100)) + "%"
    file_dict[filename[0] + os.sep + filename[1]] = [line_num, annotation_num, annotation_proportion]
    global file_list
    # 重新排序 
    file_list = sorted(file_dict.items(), key=lambda b: b[1][0], reverse=True)

Python很有趣
玩的很开心啊,哈哈哈哈
源码有点烂没好意思全贴,想要的跟我说我贴上来。。。
或者我优化优化在贴上来啊,哈哈哈哈哈哈

上一篇下一篇

猜你喜欢

热点阅读