helper.py 11.7 KB
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1
import os
每日一练社区's avatar
每日一练社区 已提交
2
import re
每日一练社区's avatar
每日一练社区 已提交
3 4 5
import sys
import uuid
import json
每日一练社区's avatar
每日一练社区 已提交
6
import shutil
每日一练社区's avatar
每日一练社区 已提交
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


def get_files_path(file_dir, filetype='.txt'):
    """得到文件夹下的所有.txt文件的路径
    Args:
        file_dir: 文件夹路径
        filetype: 文件后缀
    Returns:
        所有filetype类型文件的绝对路径
    """
    files_path = []
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            if filetype is None or (os.path.splitext(file)[1] == filetype):
                files_path.append(os.path.join(root, file))
    return files_path


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 classify_exercises():
    language_ext = {
        'cpp': '.cpp',
        'java': '.java',
        'python': '.py'
    }
每日一练社区's avatar
每日一练社区 已提交
53
    
每日一练社区's avatar
每日一练社区 已提交
54 55
    answer_dirs = ['data_backup/cpp_code_json', 'data_backup/java_code_json', 'data_backup/python_code_json']
    for dir in answer_dirs:
每日一练社区's avatar
每日一练社区 已提交
56 57 58
        count_simple = 0
        count_middle = 0
        count_diff = 0
每日一练社区's avatar
每日一练社区 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
        language = dir.split('/')[-1].split('_')[0]
        ext = language_ext[language]
        files = get_files_path(dir, '.json')
        for file_path in files:
            data = load_json(file_path)
            status = data['status']
            if status == 0:
                continue
            difficulty = data['difficulty']
            question_title = data['question_title']
            question_content = data['question_content']
            answer = data[language]
            license = data['license']
            keywords = data['keywords']

            config_data = {}
            config_data['node_id'] = 'dailycode-' + uuid.uuid4().hex
            config_data['keywords'] = []
            config_data['children'] =[]
            config_data['export'] = ["solution.json"]

            solution_json_data = {}
            solution_json_data['type'] = 'code_options'
            solution_json_data['author'] = 'csdn.net'
            solution_json_data['source'] = 'solution.md'
            solution_json_data['exercise_id'] = uuid.uuid4().hex
每日一练社区's avatar
每日一练社区 已提交
85
            solution_json_data['keywords'] = keywords
每日一练社区's avatar
每日一练社区 已提交
86 87

            solution_md_data = f"# {question_title}\n\n{question_content}\n\n## template\n\n```{language}\n{answer}\n```\n\n## 答案\n\n```{language}\n\n```\n\n## 选项\n\n### A\n\n```{language}\n\n```\n\n### B\n\n```{language}\n\n```\n\n### C\n\n```{language}\n\n```"
每日一练社区's avatar
每日一练社区 已提交
88 89 90
            # print(solution_md_data)
            # print(config_data)
            # print(solution_json_data)
每日一练社区's avatar
每日一练社区 已提交
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111


            if difficulty == '简单':
                root_dir = 'data/1.dailycode初阶'
            elif difficulty == '中等':
                root_dir = 'data/2.dailycode中阶'
            elif difficulty == '困难':
                root_dir = 'data/3.dailycode高阶'
            else:
                root_dir = ''
                sys.exit("难度等级异常")
            if language == 'cpp':
                language_dir = '1.' + language
            elif language == 'java':
                language_dir = '2.' + language
            elif language == 'python':
                language_dir = '3.' + language
            else:
                language_dir = ''
                sys.exit("语言类型异常")
            dst_dir = os.path.join(root_dir, language_dir)
每日一练社区's avatar
每日一练社区 已提交
112 113 114 115 116 117 118 119 120 121
            if difficulty == '简单':
                count_simple +=1
                exercises_dir = os.path.join(dst_dir, str(count_simple) + '.exercises')
            elif difficulty == '中等':
                count_middle +=1
                exercises_dir = os.path.join(dst_dir, str(count_middle) + '.exercises')
            elif difficulty == '困难':
                count_diff +=1
                exercises_dir = os.path.join(dst_dir, str(count_diff) + '.exercises')
            print(exercises_dir)
每日一练社区's avatar
每日一练社区 已提交
122

每日一练社区's avatar
每日一练社区 已提交
123 124 125 126 127 128 129
            solution_json_path = os.path.join(exercises_dir, 'solution.json')
            solution_md_path = os.path.join(exercises_dir, 'solution.md')
            config_path = os.path.join(exercises_dir, 'config.json')


            if not os.path.exists(exercises_dir):
                os.makedirs(exercises_dir)
每日一练社区's avatar
每日一练社区 已提交
130 131 132 133
            dump_json(solution_json_path, solution_json_data)
            dump_json(config_path, config_data)
            with open(solution_md_path, 'w', encoding='utf-8') as f:
                f.write(solution_md_data)
每日一练社区's avatar
每日一练社区 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164

def classify_leetcode():
    leetcode_dir = 'data_backup/leetcode'
    files = get_files_path(leetcode_dir, '.json')
    for file in files:
        for language in ['java', 'python', 'cpp']:
            data = load_json(file)
            status = data['status']
            if status == 0:
                continue
            difficulty = data['difficulty']
            question_title = data['question_title']
            question_content = data['question_content']
            answer = data[language]
            license = data['license'][language]
            keywords = data['keywords']

            config_data = {}
            config_data['node_id'] = 'dailycode-' + uuid.uuid4().hex
            config_data['keywords'] = []
            config_data['children'] =[]
            config_data['export'] = ["solution.json"]

            solution_json_data = {}
            solution_json_data['type'] = 'code_options'
            if language == 'java':
                solution_json_data['author'] = 'csdn.net'
            else:
                solution_json_data['author'] = license
            solution_json_data['source'] = 'solution.md'
            solution_json_data['exercise_id'] = uuid.uuid4().hex
每日一练社区's avatar
每日一练社区 已提交
165
            solution_json_data['keywords'] = keywords
每日一练社区's avatar
每日一练社区 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189

            solution_md_data = f"# {question_title}\n\n{question_content}\n\n## template\n\n```{language}\n{answer}\n```\n\n## 答案\n\n```{language}\n\n```\n\n## 选项\n\n### A\n\n```{language}\n\n```\n\n### B\n\n```{language}\n\n```\n\n### C\n\n```{language}\n\n```"

            # print(solution_md_data)
            # print(config_data)
            # print(solution_json_data)
            if difficulty == '简单':
                root_dir = 'data/1.dailycode初阶'
            elif difficulty == '中等':
                root_dir = 'data/2.dailycode中阶'
            elif difficulty == '困难':
                root_dir = 'data/3.dailycode高阶'
            else:
                root_dir = ''
                sys.exit("难度等级异常")
            if language == 'cpp':
                language_dir = '1.' + language
            elif language == 'java':
                language_dir = '2.' + language
            elif language == 'python':
                language_dir = '3.' + language
            else:
                language_dir = ''
                sys.exit("语言类型异常")
每日一练社区's avatar
每日一练社区 已提交
190 191 192
            current_dst_dir = os.path.join(root_dir, language_dir)
            print(current_dst_dir)
            dir_list_ = os.listdir(current_dst_dir)
每日一练社区's avatar
每日一练社区 已提交
193 194
            dir_list = []
            for i in dir_list_:
每日一练社区's avatar
每日一练社区 已提交
195 196 197
                current_dst_dir_ = os.path.join(current_dst_dir, i)
                if os.path.isdir(current_dst_dir_):
                    dir_list.append(current_dst_dir_)
每日一练社区's avatar
每日一练社区 已提交
198
            number = len(dir_list) + 1
每日一练社区's avatar
每日一练社区 已提交
199 200
            dst_dir = os.path.join(current_dst_dir, str(number) + '.exercises')

每日一练社区's avatar
每日一练社区 已提交
201 202 203 204 205
            solution_json_path = os.path.join(dst_dir, 'solution.json')
            solution_md_path = os.path.join(dst_dir, 'solution.md')
            config_path = os.path.join(dst_dir, 'config.json')


每日一练社区's avatar
每日一练社区 已提交
206 207 208 209 210 211
            if not os.path.exists(dst_dir):
                os.mkdir(dst_dir)
            dump_json(solution_json_path, solution_json_data)
            dump_json(config_path, config_data)
            with open(solution_md_path, 'w', encoding='utf-8') as f:
                f.write(solution_md_data)
每日一练社区's avatar
每日一练社区 已提交
212

每日一练社区's avatar
每日一练社区 已提交
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
def rename_dir():
    dirs = ['data/1.dailycode初阶', 'data/2.dailycode中阶', 'data/3.dailycode高阶']
    for dir in dirs:
        lanuages_dirs = ['1.cpp', '2.java', '3.python']
        for lanuages_dir in lanuages_dirs:
            lanuages_dir = os.path.join(dir, lanuages_dir)
            # print(lanuages_dir)
            exercises_dirs = os.listdir(lanuages_dir)
            print(exercises_dirs)
            for idx, exer in enumerate(exercises_dirs):
                exercises_dir = os.path.join(lanuages_dir, exer)
                new_exercises_dir = os.path.join(lanuages_dir, '{}.exercises'.format(idx + 1))
                # print(exercises_dir)
                # print(new_exercises_dir)
                # os.rename(exercises_dir, new_exercises_dir)

每日一练社区's avatar
每日一练社区 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
def extract_it_knowledge():
    data_dir = 'data_backup/it_knowledge'
    files = get_files_path(data_dir, '.md')
    language = 'json'
    for file in files:
        with open(file, 'r', encoding='utf-8') as f:
            data = f.read()
            file_name = file.split('/')[-1].split('.')[0]
            # print(file_name)
            # print(data)

            question_title = re.findall(r'## 标题\n(.*?)\n##', data, re.S)[0]
            question_title = question_title.strip()
            # print(question_title)
            question_content = re.findall(r'## 描述\n(.*?)\n##', data, re.S)[0]
            question_content = question_content.strip()
            # if question_content == []:
            #     print(file)
            keywords = re.findall(r'## 关键词\n(.*?)\n##', data, re.S)[0]
            keywords = keywords.strip()
            keywords_list = keywords.split(';')
            keywords = ','.join(keywords_list)
            # print(keywords)
            topic_link = re.findall(r'## 链接\n(.*?)\n##', data, re.S)[0]
            topic_link = topic_link.strip()
            # print(topic_link)
            difficulty = '简单'
            choice = re.findall(r'## 选项\n(.*?)\n##', data, re.S)[0]
            
            choice_list = choice.split('\n')
            choice_list_res = []
            for tem in choice_list:
                if tem == '':
                    continue
                else:
                    tem = tem.strip()
                    choice_list_res.append(tem)

            # print(choice_list_res)
            
            answer = re.findall(r'## 答案\n(.*)', data, re.S)[0]
            answer = answer.strip()
            print(file)
            assert answer in choice_list_res
            question_id = file_name
            choice_list_remove = []
            for idx, val in enumerate(choice_list_res):
                if val == answer:
                    answer_idx = idx
                    continue
                else:
                    choice_list_remove.append(val)
        
        
        config_data = {}
        config_data['node_id'] = 'dailycode-' + uuid.uuid4().hex
        config_data['keywords'] = []
        config_data['children'] =[]
        config_data['export'] = ["solution.json"]

        solution_json_data = {}
        solution_json_data['type'] = 'code_options'
        solution_json_data['author'] = 'csdn.net'
        solution_json_data['source'] = 'solution.md'
        solution_json_data['exercise_id'] = uuid.uuid4().hex
        solution_json_data['keywords'] = keywords
        solution_json_data['topic_link'] = topic_link


        solution_md_data = f"# {question_title}\n\n{question_content}\n\n## 答案\n\n```{language}\n{answer}\n```\n\n## 选项\n\n### A\n\n```{language}\n{choice_list_remove[0]}\n```\n\n### B\n\n```{language}\n{choice_list_remove[1]}\n```\n\n### C\n\n```{language}\n{choice_list_remove[2]}\n```"
        print(solution_md_data)

每日一练社区's avatar
每日一练社区 已提交
301

每日一练社区's avatar
每日一练社区 已提交
302
classify_leetcode()
每日一练社区's avatar
每日一练社区 已提交
303 304


每日一练社区's avatar
每日一练社区 已提交
305

每日一练社区's avatar
每日一练社区 已提交
306
# classify_leetcode()