您的位置:首页 > 编程语言 > Python开发

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

2020-12-31 18:31 399 查看

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

安装
pip3 install

U handout

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

"""

# Python Handout库

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

"""
import
handout

import
matplotlib
.
pyplot
as
plt

import
numpy
as
np
"""## 定义输出的文件夹"""
doc
=
handout
.
Handout
(
'output'
)
"""

## Markdown注释

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

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

-

Headlines

-

Hyperlinks

-

Inline

`code()`
snippets

-

**
Bold
**

and

*
italic
*

"""

"""

## 添加文本和变量

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

"""
for
index
in
range
(
3
):

doc
.
add_text
(
'Iteration'
,
index
)

doc
.
show
()
"""

## 添加matplotlib图

在handout中添加matplotlib图

"""
fig
,
ax
=
plt
.
subplots
(
figsize
=(
4
,

3
))

ax
.
plot
(
np
.
arange
(
100
))

fig
.
tight_layout
()

doc
.
add_figure
(
fig
)

doc
.
show
()
"""

设置handout中图片的尺寸

"""
for
iteration
in
range
(
3
):

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

2
))

ax
.
plot
(
np
.
sin
(
np
.
linspace
(
0
,

20

/

(
iteration
+

1
),

100
)))

doc
.
add_figure
(
fig
,
width
=
0.33
)

doc
.
show
()
"""

## 添加图片

This requires the `imageio` pip package.

"""
image_a
=
np
.
random
.
uniform
(
0
,

255
,

(
200
,

400
,

3
)).
astype
(
np
.
uint8
)

image_b
=
np
.
random
.
uniform
(
0
,

255
,

(
100
,

200
,

1
)).
astype
(
np
.
uint8
)

doc
.
add_image
(
image_a
,

'png'
,
width
=
0.4
)

doc
.
add_image
(
image_b
,

'jpg'
,
width
=
0.4
)

doc
.
show
()
"""

## 浏览handout

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

"""

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

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐