forked from lijin-THU/notes-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_static_files.py
92 lines (54 loc) · 1.77 KB
/
generate_static_files.py
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
# coding: utf-8
# # 将笔记转化为不同的文件格式
# In[ ]:
import os
import os.path
import nbconvert
import glob
# 检查路径是否存在,删除旧的文件:
# In[ ]:
if not os.path.exists('static-files'):
os.mkdir('static-files')
for n in glob.glob('static-files/*/*/*'):
os.remove(n)
# 文件夹:
# In[ ]:
folders = ['01-python-tools',
'02-python-essentials',
'03-numpy',
'04-scipy',
'05-advanced-python',
'06-matplotlib',
'07-interfacing-with-other-languages',
'08-object-oriented-programming',
'09-theano',
'10-something-interesting',
'11-useful-tools',
'12-pandas'
]
# 遍历文件夹得到所有的文件名:
# In[ ]:
file_names = []
for folder in folders:
files = sorted(os.listdir(folder))
file_names += [os.path.join(folder, file_name) for file_name in files if file_name.endswith('.ipynb')]
# In[ ]:
def convert_to_files(names, to_format):
target_dir = os.path.join("static-files", to_format)
for folder in folders:
if not os.path.exists(os.path.join(target_dir, folder)):
os.makedirs(os.path.join(target_dir, folder))
for file_name in names:
p = nbconvert.export(nbconvert.get_exporter(to_format), file_name)
with open(os.path.join(target_dir, file_name[:-6] + p[1]["output_extension"]), 'w') as f:
f.write(p[0].encode("utf-8"))
print file_name
# 转化 HTML 文件:
# In[ ]:
convert_to_files(file_names, "html")
# 产生新目录:
# In[ ]:
with open('index.md') as f:
text = f.read()
with open(os.path.join("static-files", "html", "README.md"), "w") as g:
g.write(text.replace(".ipynb", ".html"))