分享

Handout库:能将python脚本转化为html展示文件

 大邓的Python 2021-02-23

有的时候我们需要将python代码进行展示讲解,这个时候使用py文件进行讲解效果并不是最好的。如果能转化为html文件,在浏览器中展示,那就完美了。好消息是存在一个名为handout的库可以实现我们的设想。

安装

  1. pip3 install -U handout

快速学习

下面是demo.py文件中的代码及注释,其中handout库可以将注释部分中的markdown标记转化为html相应的样式

  1. """

  2. # Python Handout库

  3. 将python脚本转化为带markdown标记形式的html文件

  4. """

  1. import handout

  2. import matplotlib.pyplot as plt

  3. import numpy as np

  1. """## 定义输出的文件夹"""

  1. doc = handout.Handout('output')

  1. """

  2. ## Markdown注释

  3. 以前后3个"内的部分作为markdown待识别区域,可以用markdown语法书写注释

  4. 例如,handout中出现下面的无序列表

  5. - Headlines

  6. - Hyperlinks

  7. - Inline `code()` snippets

  8. - **Bold** and *italic*

  9. """

  10. """

  11. ## 添加文本和变量

  12. 注意这里使用doc.add_text方法向handout中添加运行结果,类似于python中的print

  13. """

  1. for index in range(3):

  2. doc.add_text('Iteration', index)

  3. doc.show()

  1. """

  2. ## 添加matplotlib图

  3. 在handout中添加matplotlib图

  4. """

  1. fig, ax = plt.subplots(figsize=(4, 3))

  2. ax.plot(np.arange(100))

  3. fig.tight_layout()

  4. doc.add_figure(fig)

  5. doc.show()

  1. """

  2. 设置handout中图片的尺寸

  3. """

  1. for iteration in range(3):

  2. fig, ax = plt.subplots(figsize=(3, 2))

  3. ax.plot(np.sin(np.linspace(0, 20 / (iteration + 1), 100)))

  4. doc.add_figure(fig, width=0.33)

  5. doc.show()

  1. """

  2. ## 添加图片

  3. This requires the `imageio` pip package.

  4. """

  1. image_a = np.random.uniform(0, 255, (200, 400, 3)).astype(np.uint8)

  2. image_b = np.random.uniform(0, 255, (100, 200, 1)).astype(np.uint8)

  3. doc.add_image(image_a, 'png', width=0.4)

  4. doc.add_image(image_b, 'jpg', width=0.4)

  5. doc.show()

  1. """

  2. ## 浏览handout

  3. 默认doc.show()输出到output文件夹中的index.html文件

  4. """

输出结果

下面左侧是代码,右侧是转化后的html文件效果。

下面是demo.py文件的运行过程及结果的动态展示

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多