|
| 1 | +from itertools import pairwise |
1 | 2 | import os
|
2 | 3 | import re
|
3 | 4 |
|
|
24 | 25 | # 抽取代码块
|
25 | 26 | def extract_code():
|
26 | 27 | paths = []
|
27 |
| - suffixes = [suf for _, (_, suf) in code_block_dict.items()] |
28 | 28 | for root, _, files in os.walk(os.getcwd()):
|
29 | 29 | for file in files:
|
30 | 30 | path = root + "/" + file
|
@@ -58,5 +58,66 @@ def extract_code():
|
58 | 58 | cnt += 1
|
59 | 59 |
|
60 | 60 |
|
| 61 | +def parse_content(content, start, end, titles): |
| 62 | + i = content.find(start) |
| 63 | + if i == -1: |
| 64 | + return [] |
| 65 | + j = content.find(end) |
| 66 | + if j == -1: |
| 67 | + return [] |
| 68 | + content = content[i + len(start) : j] |
| 69 | + blocks = [] |
| 70 | + idx = [content.find(title) for title in titles] |
| 71 | + for l, r in pairwise(idx): |
| 72 | + block = content[l:r].strip() |
| 73 | + if not block: |
| 74 | + continue |
| 75 | + line = block.split("\n")[0] |
| 76 | + method_name = line[2:-2] |
| 77 | + block = block.replace(line, f"### {method_name}") |
| 78 | + blocks.append(block) |
| 79 | + return blocks |
| 80 | + |
| 81 | + |
| 82 | +def extract_solution_paragraph(): |
| 83 | + paths = [] |
| 84 | + for root, _, files in os.walk(os.getcwd()): |
| 85 | + for file in files: |
| 86 | + path = root + "/" + file |
| 87 | + if "node_modules" in path or "__pycache__" in path or ".git" in path: |
| 88 | + continue |
| 89 | + if root == "D:\github-repo\leetcode": |
| 90 | + continue |
| 91 | + if path.endswith("README.md") or path.endswith("README_EN.md"): |
| 92 | + paths.append(path) |
| 93 | + for path in paths: |
| 94 | + with open(path, "r", encoding="utf-8") as f: |
| 95 | + content = f.read() |
| 96 | + |
| 97 | + is_cn = path.endswith("README.md") |
| 98 | + if is_cn: |
| 99 | + blocks = parse_content( |
| 100 | + content, |
| 101 | + "## 解法", |
| 102 | + "<!-- tabs:start -->", |
| 103 | + ["**方法一:", "**方法二:", "**方法三:", "**方法四:"], |
| 104 | + ) |
| 105 | + else: |
| 106 | + print(path) |
| 107 | + blocks = parse_content( |
| 108 | + content, |
| 109 | + "## Solutions", |
| 110 | + "<!-- tabs:start -->", |
| 111 | + ["**Solution 1:", "**Solution 2:", "**Solution 3:", "**Solution 4:"], |
| 112 | + ) |
| 113 | + |
| 114 | + if blocks: |
| 115 | + prefix = path[: path.rfind("/")] |
| 116 | + name = f"{prefix}/Solution.md" if is_cn else f"{prefix}/Solution_EN.md" |
| 117 | + with open(name, "w", encoding="utf-8") as f: |
| 118 | + f.write("\n\n".join(blocks)) |
| 119 | + |
| 120 | + |
61 | 121 | if __name__ == "__main__":
|
62 |
| - extract_code() |
| 122 | + # extract_code() |
| 123 | + extract_solution_paragraph() |
0 commit comments