[ python ] 老板叫我一天清出项目中所有不用的接口, 我一个小时搞定了!!

import re
import os

result = {}


# 搜索到的接口名称
def get_api_str(_file_dir):
    search_kw = []
    with open(_file_dir, "r", encoding="utf-8") as f:
        lines = f.readlines()
        for line in lines:
            if line.startswith("export"):
                res = re.findall(r"(?<=const\s)\w+(?=\s\=)", line)
                if res and len(res):
                    search_kw.append(res[0])
    return search_kw


# 扫描文件
def scan_file(_base_dir, _result=[]):
    if os.path.isfile(_base_dir):
        # 当前是文件
        _result.append(_base_dir)
    else:
        # 当前是文件夹
        lis = os.listdir(_base_dir)
        for f in lis:
            scan_file(_base_dir + '/' + f, _result)
    return _result


# 获取文件中字段出现的次数
def get_count(_path, _str_arr):
    with open(_path, 'r', encoding='utf-8') as f:
        content = f.read()
        for _str in _str_arr:
            if _str in content:
                result[_str] += 1


if __name__ == "__main__":
    # 项目源码的位置
    BASE_DIR = r"E:\Z_CLIENT_GIT\Work\heater_webapp" + r"\src"
    # 读取的接口文件
    # API_DIR = BASE_DIR + r"\api\blower.js"
    # API_DIR = BASE_DIR + r"\api\charge.js"
    # API_DIR = BASE_DIR + r"\api\common.js"
    # API_DIR = BASE_DIR + r"\api\shower.js"
    # API_DIR = BASE_DIR + r"\api\washer.js"
    # API_DIR = BASE_DIR + r"\api\water.js"
    API_DIR = BASE_DIR + r"\api\index.js"
    # 期望在哪些文件[夹]下寻找出现的字段

    # 拿到接口对应的名称
    api_list = get_api_str(API_DIR)

    # 拿到目录下的所有文件列表
    total_files = scan_file(BASE_DIR)

    for i in api_list:
        result[i] = 0

    for file in total_files:
        if file.endswith(('vue', 'js')):
            get_count(file, api_list)

    for i in api_list:
        font = '仅出现1次' if result[i] == 1 else ""
        print(f"{i.ljust(32, ' ')}{result[i]}次     {font}")

接口查重

 

项目基本上是vue写的, 有的是uniapp, 但是项目结果基本上相同

如果一个接口一个接口的 Ctrl+shift+f 的全局搜索, 估计需要很久的时间

所以想出了用 python 这种脚本一次性的过滤只出现过一次的接口, 一个小时就筛出结果来了

 

拿到结果之后再去vscode里面全局搜索, 二次确定一下, 然后  可以下班了~

 

posted @ 2025-08-06 14:48  深海里的星星i  阅读(2)  评论(0)    收藏  举报