A Code Analysis Function Implemented by Python

The main functions are as follows:
  1. Code Statistics of Single Page and Total Lines
  2. Annotation Statistics of Single Page and Total Lines
  3. Statistics of Code Annotation Rate and Total Annotation Rate
  4. Sort by comment rate/number of lines of comment/number of lines of code
  5. Annotation analysis according to annotation mode "/""<!-->" #""/***/"- > for the time being only these
  • The basic grammar of off-topic Python is very easy to learn, and it is difficult to use various modules. The strength of Python lies in these modules, which have a long way to go.

  • Originally, I wanted to use PyQt5 to write an executable file. After all, I am an Android or I want my code to have a nice UI. After reading the document of PyQt5, I gave up, and I still need time to learn its usage (=====). Nonsense), and I don't have time to learn now, let's talk about it later.~

  • In the case of Android's source code, the annotation ratio is still high (folders / files are used to prevent class renaming statistics from losing accuracy).

    QQ screenshot 2010 70907195035.png
  • Let's talk about the process.

1. Traversing folders
    # start
    traverse_files(root)
    print("Total number of banks", code_num, 'Number of annotation rows', code_annotation_num, 'Annotation scale',
          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],
              "Number of file rows:%s" % item[1][0],
              "Number of comment lines:%s" % item[1][1],
              "Note Ratio:%s" % item[1][2]
              )

traverse_files is a recursive function, such as filtering file suffixes and circular folders.

    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. Read files
    try:
        with open(root_path, 'r', encoding=encoding) as lineFile:
            block_list = lineFile.readlines()
            # All data that has been commented on /**/ and <!--> are not counted as comment lines.
            annotation_line_lst = []
            # Read each row into the collection
            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

                        # General java and html have such annotations
                        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(' ', '')
                                    # Judgment - > Is this the last line of the line?
                                    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
            # Save information from a single file
            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, statistics
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
    # Rescheduling 
    file_list = sorted(file_dict.items(), key=lambda b: b[1][0], reverse=True)

Python is interesting
Ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha
Source code is a bit rotten, not embarrassed to post it all, want to tell me I paste it up...
Or I optimize and optimize the poster ah, ha ha ha ha ha

Keywords: Python Java Android encoding

Added by may27 on Mon, 27 May 2019 02:29:19 +0300