md.py 4.8 KB
Newer Older
F
feilong 已提交
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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
import os
from sys import path, version
from types import new_class
from .tree import load_json, dump_json


def simple_list_md_load(p):
    with open(p, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        result = []
        for line in lines:
            item = line.strip('\n')
            result.append(item)
        return result


def simple_list_md_dump(p, lines):
    with open(p, 'w', encoding='utf-8') as f:
        f.write('\n'.join(lines))


def simple_py_load(p):
    with open(p, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        author = ''
        titles = []
        contents = []
        codes = []
        space_id = 0
        max_space_id = 0
        for i, line in enumerate(lines):
            item = line.strip('\n')
            if i == 0:
                pass
            elif i == 1:
                author = item[5:]
            elif i == 2:
                titles.append(item[5:])
            elif i == 3:
                contents.append(item[5:])
            elif item.startswith('#'):
                contents.append(item[2:])
            else:
                if item.strip() == '':
                    codes.append({
                        'space_id': space_id,
                        'code': item
                    })
                    if max_space_id < space_id:
                        max_space_id = space_id
                    space_id += 1
                else:
                    codes.append({
                        'space_id': -1,
                        'code': item
                    })

        strip_codes = []
        for line in codes:
            if line['space_id'] == 0 or line['space_id'] == max_space_id:
                pass
            else:
                strip_codes.append(line['code'])

        return {
            'author': author,
            'title': '\n'.join(titles),
            'contents': contents,
            'codes': strip_codes,
        }


class MDWalker():

    def __init__(self, root) -> None:
        self.root = root

    def walk(self):
        for base, dirs, files in os.walk(self.root):
            for file in files:
                if file[-3:] == '.py':
                    print(file)
                    py_file = os.path.join(base, file)
                    py = simple_py_load(py_file)
                    md_file = os.path.join(base, file.replace('.py', '.md'))
                    json_file = os.path.join(
                        base, file.replace('.py', '.json'))

                    print(py_file)
                    print(md_file)
                    print(json_file)

                    if os.path.exists(md_file):
F
feilong 已提交
94 95 96
                        j = load_json(json_file)
                        j['source'] = j['source'].replace('.py', '.md')
                        dump_json(json_file, j, True, True)
F
feilong 已提交
97
                        continue
F
feilong 已提交
98

F
feilong 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
                    md = []
                    self.emit_head(md, py)
                    self.emit_template(md, py)
                    self.emit_answer(md, py)
                    self.emit_options(md, py)
                    simple_list_md_dump(md_file, md)

                    if os.path.exists(json_file):
                        j = load_json(json_file)
                        if j.get('one_line'):
                            del j['one_line']
                        if j.get('multiline'):
                            del j['multiline']
                        j['author'] = py['author']
                        j['notebook_enable'] = True
F
feilong 已提交
114
                        j['source'] = j['source'].replace('.py', '.md')
F
feilong 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 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
                        dump_json(json_file, j, True, True)

    def emit_head(self, md, py):
        title = py['title']
        contents = py['contents']
        codes = py['codes']
        md.append(f'# {title}')
        md.append('')
        for content in contents:
            md.append(content)
        md.append('')
        md.append('```python')
        for code in codes:
            md.append(code)
        md.append('```')
        md.append('')
        md.append('请选出下列能**正确**实现这一功能的选项。')
        md.append('')

    def emit_template(self, md, py):
        codes = py['codes']
        md.append(f'## template')
        md.append('')
        md.append('```python')
        for code in codes:
            md.append(code)
        md.append('```')
        md.append('')

    def emit_answer(self, md, py):
        md.append(f'## 答案')
        md.append('')
        md.append('```python')
        md.append('')
        md.append('```')
        md.append('')

    def emit_options(self, md, py):
        md.append(f'## 选项')
        md.append('')

        for tag in ['A', 'B', 'C']:
            md.append(f'### {tag}')
            md.append('')
            md.append('```python')
            md.append('')
            md.append('```')
            md.append('')