|
| 1 | + |
| 2 | +# coding: utf-8 |
| 3 | + |
| 4 | +# # 将笔记转化为不同的文件格式 |
| 5 | + |
| 6 | +# In[1]: |
| 7 | + |
| 8 | +import os |
| 9 | +import os.path |
| 10 | +import nbconvert |
| 11 | + |
| 12 | + |
| 13 | +# 检查路径是否存在: |
| 14 | + |
| 15 | +# In[2]: |
| 16 | + |
| 17 | +if not os.path.exists('static files'): |
| 18 | + os.mkdir('static files') |
| 19 | + |
| 20 | + |
| 21 | +# 文件夹: |
| 22 | + |
| 23 | +# In[3]: |
| 24 | + |
| 25 | +folders = ['01. python tools', |
| 26 | + '02. python essentials', |
| 27 | + '03. numpy', |
| 28 | + '04. scipy', |
| 29 | + '05. advanced python', |
| 30 | + '06. matplotlib', |
| 31 | + '07. interfacing with other languages', |
| 32 | + '08. object-oriented programming', |
| 33 | + '09. theano', |
| 34 | + '10. something interesting', |
| 35 | + '11. useful tools' |
| 36 | + ] |
| 37 | + |
| 38 | + |
| 39 | +# 遍历文件夹得到所有的文件名: |
| 40 | + |
| 41 | +# In[4]: |
| 42 | + |
| 43 | +file_names = [] |
| 44 | + |
| 45 | +for folder in folders: |
| 46 | + files = sorted(os.listdir(folder)) |
| 47 | + file_names += [os.path.join(folder, file_name) for file_name in files if file_name.endswith('.ipynb')] |
| 48 | + |
| 49 | + |
| 50 | +# In[5]: |
| 51 | + |
| 52 | +def convert_to_files(names, to_format): |
| 53 | + target_dir = os.path.join("static files", to_format) |
| 54 | + for folder in folders: |
| 55 | + if not os.path.exists(os.path.join(target_dir, folder)): |
| 56 | + os.makedirs(os.path.join(target_dir, folder)) |
| 57 | + converter = { |
| 58 | + "html": nbconvert.export_html, |
| 59 | + "python": nbconvert.export_python |
| 60 | + } |
| 61 | + |
| 62 | + for file_name in names: |
| 63 | + p = converter[to_format](file_name) |
| 64 | + with open(os.path.join(target_dir, file_name[:-6] + p[1]["output_extension"]), 'w') as f: |
| 65 | + f.write(p[0].encode("utf-8")) |
| 66 | + print file_name |
| 67 | + |
| 68 | + |
| 69 | +# 转化 HTML 文件: |
| 70 | + |
| 71 | +# In[6]: |
| 72 | + |
| 73 | +convert_to_files(file_names, "html") |
| 74 | + |
| 75 | + |
| 76 | +# 产生新目录: |
| 77 | + |
| 78 | +# In[7]: |
| 79 | + |
| 80 | +with open('index.md') as f: |
| 81 | + text = f.read() |
| 82 | + with open(os.path.join("static files/html", "README.md"), "w") as g: |
| 83 | + g.write(text.replace(".ipynb", ".html")) |
| 84 | + |
0 commit comments