使用Python将Markdown表转换为html表

2024-09-27 07:29:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个降价表语法字符串,比如:

table_md=\
"| Tables        | Are           | Cool  |\n\
| ------------- |-------------| -----|\n\
| col 3 is      | right-aligned | $1600 |\n\
| col 2 is      | centered      |   $12 |\n\
| zebra stripes | are neat      |    $1 |\n"

我想转换它的字符串语法:

^{pr2}$

首先搜索stackoverflow,我尝试使用this

import markdown
table_html=markdown.markdown(table_md)

但结果是一个html段落:

'<p>| Tables...    |</p>'

通过搜索这个问题,我找到了markdown extensions,并尝试将扩展添加到上面的命令中:

table_html=markdown.markdown(table_md, extensions=[MyExtension(), \
'markdown.extensions.tables'])

然后显示错误消息"NameError: name 'MyExtension' is not defined"

stackoverflow中没有相同的情况。在

请帮我怎么处理上面的MyExtension。谢谢您!在


Tags: 字符串tablesishtmltable语法extensionscol
2条回答

我找到了解决方案,extension library声明“扩展列表可能包含扩展的实例和/或扩展名的字符串”,因此MyExtension()是可选的,因此我可以删除它在这种情况下,解决方案是:

table_html=markdown.markdown(table_md, extensions=['markdown.extensions.tables'])

对于那些想要添加自己的添加或更改Markdown语法的用户,可以使用MyExtension,如下所示:

^{pr2}$

首先,您可以输入如下内容:

table_md="| Tables        | Are           | Cool  |\n\
|       - |      -|   -|\n\
| col 3 is      | right-aligned | $1600 |\n\
| col 2 is      | centered      |   $12 |\n\
| zebra stripes | are neat      |    $1 |\n"

使用扩展名markdown.extensions.tables

^{pr2}$

输出为:

>>> print table_html
<table>
<thead>
<tr>
<th>Tables</th>
<th>Are</th>
<th>Cool</th>
</tr>
</thead>
<tbody>
<tr>
<td>col 3 is</td>
<td>right-aligned</td>
<td>$1600</td>
</tr>
<tr>
<td>col 2 is</td>
<td>centered</td>
<td>$12</td>
</tr>
<tr>
<td>zebra stripes</td>
<td>are neat</td>
<td>$1</td>
</tr>
</tbody>
</table>

相关问题 更多 >

    热门问题