-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathconvert_md_to_docx.py
More file actions
103 lines (85 loc) · 3.69 KB
/
convert_md_to_docx.py
File metadata and controls
103 lines (85 loc) · 3.69 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
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
94
95
96
97
98
99
100
101
102
103
import re
import requests
import os
from docx import Document
from docx.shared import Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
def download_image(url, filename):
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Referer': 'https://www.shiyanlou.com/'
}
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
with open(filename, 'wb') as f:
f.write(response.content)
return True
except Exception as e:
print(f"Failed to download {url}: {e}")
return False
def markdown_to_docx(md_file, docx_file):
with open(md_file, 'r', encoding='utf-8') as f:
content = f.read()
doc = Document()
lines = content.split('\n')
i = 0
while i < len(lines):
line = lines[i].strip()
if line.startswith('---'):
i += 1
continue
if line.startswith('#'):
level = len(re.match(r'^#+', line).group())
text = re.sub(r'^#+\s*', '', line)
heading = doc.add_heading(text, level=min(level, 9))
heading.alignment = WD_ALIGN_PARAGRAPH.LEFT
elif line.startswith('!['):
match = re.match(r'!\[([^\]]*)\]\(([^)]+)\)', line)
if match:
alt_text = match.group(1)
img_url = match.group(2)
img_filename = f"temp_img_{i}.png"
if download_image(img_url, img_filename):
try:
doc.add_picture(img_filename, width=Inches(5))
last_paragraph = doc.paragraphs[-1]
last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
os.remove(img_filename)
except Exception as e:
print(f"Failed to insert image: {e}")
if os.path.exists(img_filename):
os.remove(img_filename)
elif line.startswith('- ['):
match = re.match(r'- \[([^\]]+)\]\(([^)]+)\)', line)
if match:
link_text = match.group(1)
link_url = match.group(2)
p = doc.add_paragraph(link_text, style='List Bullet')
p.add_run(f" ({link_url})")
else:
if line.startswith('-'):
text = re.sub(r'^-\s*', '', line)
doc.add_paragraph(text, style='List Bullet')
elif line.startswith('-'):
text = re.sub(r'^-\s*', '', line)
doc.add_paragraph(text, style='List Bullet')
elif line.startswith('*'):
text = re.sub(r'^\*\s*', '', line)
doc.add_paragraph(text, style='List Bullet')
elif line.startswith('`'):
code_text = re.sub(r'`', '', line)
run = doc.add_paragraph().add_run(code_text)
run.font.name = 'Courier New'
elif line.strip() == '':
doc.add_paragraph()
else:
if line:
doc.add_paragraph(line)
i += 1
doc.save(docx_file)
print(f"Successfully created {docx_file}")
if __name__ == "__main__":
md_file = "/Users/easyo/Documents/oeasy/lanqiao/oeasy-python-tutorial/md/001-87321-先跑起来_python_三大系统选择_windows_mac_linux.sy.md"
docx_file = "/Users/easyo/Documents/oeasy/lanqiao/oeasy-python-tutorial/md/001-87321-先跑起来_python_三大系统选择_windows_mac_linux.sy.docx"
markdown_to_docx(md_file, docx_file)