add_number.py 2.1 KB
Newer Older
L
luxin 已提交
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
import json
import os
import re
import ipdb

def load_json(path):
    """ load_json(path:str)->jsObject
    从指定文件读取内容,解析为 json 返回
    @param path: 文件路径
    @return: 解析后的 json
    """
    with open(path) as f:
        data = f.read()
        return json.loads(data)


def dump_json(path, data):
    """ dump_json(path:str, data:obj)->None
    从指定文件读取内容,解析为 json 返回
    @param path: 文件路径
    @param data: json 对象
    @return: None
    """
    with open(path, "w+") as df:
        df.write(json.dumps(data, indent=2, ensure_ascii=False))


def add_number():
    data_root_dir = "./data"
    data_level_dir_list = [
        os.path.join(data_root_dir, _dir) for _dir in os.listdir(data_root_dir)]
    for data_level_dir in data_level_dir_list:
        if os.path.isfile(data_level_dir) is True:
            continue
        _1st_layer_dir_list = [
            os.path.join(data_level_dir, _dir) for _dir in os.listdir(data_level_dir)]
        for _1st_layer_dir in _1st_layer_dir_list:
            if _1st_layer_dir.find("leetcode") == -1:
                continue
            _2nd_layer_dir_list = [
                os.path.join(_1st_layer_dir, _dir) for _dir in os.listdir(_1st_layer_dir)]
            for _2nd_layer_dir in _2nd_layer_dir_list:
                if os.path.isfile(_2nd_layer_dir) is True:
                    continue
                _basename = os.path.basename(_2nd_layer_dir)
                _basename = re.sub(r"^[0-9]{1,3}?\.", "", _basename)
                number = str(_basename.split("-")[0])
                config_file_name = os.path.join(_2nd_layer_dir, "config.json")
                config = load_json(config_file_name)
                for index, item in enumerate(config["keywords_must"]):
                    if isinstance(item, list):
                        if number in item:
                            continue
                        item.append(number)
                        config["keywords_must"][index] = item
                dump_json(config_file_name, config)


def main():
    add_number()


if __name__=="__main__":
    main()