Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add script to extract solution description #2213

Merged
merged 1 commit into from
Jan 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
feat: add script to extract solution description
  • Loading branch information
yanglbme committed Jan 13, 2024
commit ee53352a0bc349d130236301d1927d62c9de94b9
65 changes: 63 additions & 2 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from itertools import pairwise
import os
import re

Expand All @@ -24,7 +25,6 @@
# 抽取代码块
def extract_code():
paths = []
suffixes = [suf for _, (_, suf) in code_block_dict.items()]
for root, _, files in os.walk(os.getcwd()):
for file in files:
path = root + "/" + file
Expand Down Expand Up @@ -58,5 +58,66 @@ def extract_code():
cnt += 1


def parse_content(content, start, end, titles):
i = content.find(start)
if i == -1:
return []
j = content.find(end)
if j == -1:
return []
content = content[i + len(start) : j]
blocks = []
idx = [content.find(title) for title in titles]
for l, r in pairwise(idx):
block = content[l:r].strip()
if not block:
continue
line = block.split("\n")[0]
method_name = line[2:-2]
block = block.replace(line, f"### {method_name}")
blocks.append(block)
return blocks


def extract_solution_paragraph():
paths = []
for root, _, files in os.walk(os.getcwd()):
for file in files:
path = root + "/" + file
if "node_modules" in path or "__pycache__" in path or ".git" in path:
continue
if root == "D:\github-repo\leetcode":
continue
if path.endswith("README.md") or path.endswith("README_EN.md"):
paths.append(path)
for path in paths:
with open(path, "r", encoding="utf-8") as f:
content = f.read()

is_cn = path.endswith("README.md")
if is_cn:
blocks = parse_content(
content,
"## 解法",
"<!-- tabs:start -->",
["**方法一:", "**方法二:", "**方法三:", "**方法四:"],
)
else:
print(path)
blocks = parse_content(
content,
"## Solutions",
"<!-- tabs:start -->",
["**Solution 1:", "**Solution 2:", "**Solution 3:", "**Solution 4:"],
)

if blocks:
prefix = path[: path.rfind("/")]
name = f"{prefix}/Solution.md" if is_cn else f"{prefix}/Solution_EN.md"
with open(name, "w", encoding="utf-8") as f:
f.write("\n\n".join(blocks))


if __name__ == "__main__":
extract_code()
# extract_code()
extract_solution_paragraph()