- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPython Code Extractor.py
More file actions
Latest commit
39 lines (31 loc) · 1.92 KB
/
Copy pathPython Code Extractor.py
File metadata and controls
39 lines (31 loc) · 1.92 KB
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
importos
importre
importargparse
defextract_python_code(markdown_text):
"""Extracts all Python code blocks from a given markdown text."""
returnre.findall(r'```python(.*?)```', markdown_text, re.DOTALL)
defprocess_markdown_files(directory, output_directory=None):
"""Processes markdown files and extracts Python code into separate .py files."""
ifoutput_directoryandnotos.path.exists(output_directory):
os.makedirs(output_directory)
forroot, _, filesinos.walk(directory):
forfileinfiles:
iffile.endswith('.md'): # Only process Markdown files
file_path=os.path.join(root, file)
withopen(file_path, 'r', encoding='utf-8') asf:
markdown_text=f.read()
code_blocks=extract_python_code(markdown_text)
foridx, codeinenumerate(code_blocks):
# Create a unique filename based on the markdown file name and block index
code_filename=f"{os.path.splitext(file)[0]}_{idx+1}.py"
code_filepath=os.path.join(output_directoryifoutput_directoryelseroot, code_filename)
# Save the extracted Python code
withopen(code_filepath, 'w', encoding='utf-8') ascode_file:
code_file.write(code.strip())
print(f"Extracted: {code_filepath}")
if__name__=="__main__":
parser=argparse.ArgumentParser(description="Extract Python code blocks from Markdown files.")
parser.add_argument("directory", help="Path to the directory containing Markdown files.")
parser.add_argument("--output", "-o", help="Optional output directory for extracted code files.", default=None)
args=parser.parse_args()
process_markdown_files(args.directory, args.output)