Pythonでmarkdownをhtmlにコンバートする


マークダウンをhtmlにコンバートする方法を探していた。pipで入れられるmarkdownがよさそうなので少し試してみる。

pyenvで入れた環境

$ python --version
Python 3.6.5
$ pip --version
pip 19.1.1 from /Users/ito_masakuni/.pyenv/versions/3.6.5/lib/python3.6/site-packages/pip (python 3.6)

インストール

$ pip install markdown
Collecting markdown
  Downloading https://files.pythonhosted.org/packages/c0/4e/fd492e91abdc2d2fcb70ef453064d980688762079397f779758e055f6575/Markdown-3.1.1-py2.py3-none-any.whl (87kB)
    100% |████████████████████████████████| 92kB 5.8MB/s
Requirement already satisfied: setuptools>=36 in /Users/ito_masakuni/.pyenv/versions/3.6.5/lib/python3.6/site-packages (from markdown) (39.0.1)
Installing collected packages: markdown
Successfully installed markdown-3.1.1

下記のスクリプトを書いた。


import markdown

sample_text = '''
# h1の文字が出てくると嬉しい

---

## h2の文字はでてくるだろう

* リスト1
* リスト2
* リスト3

> 引用してくれ

本文で **太字にもなるし**、*斜体にもなるはず* 。

```
まさかコードも入れられるんですか?
if (!lie) {
    return true;
}
```

| header1 | header2 | header3 |
|:-----------|------------:|:------------:|
| 左寄せ | 右寄せ | 中央寄せ |

すごい!
'''

md = markdown.Markdown()
print(md.convert(sample_text))

で、アウトプットはこうなった。

$ python md.py
<h1>h1の文字が出てくると嬉しい</h1>
<hr />
<h2>h2の文字はでてくるだろう</h2>
<ul>
<li>リスト1</li>
<li>リスト2</li>
<li>リスト3</li>
</ul>
<blockquote>
<p>引用してくれ</p>
</blockquote>
<p>本文で <strong>太字にもなるし</strong>、<em>斜体にもなるはず</em> 。</p>
<p><code>まさかコードも入れられるんですか?
if (!lie) {
    return true;
}</code></p>
<p>| header1 | header2 | header3 |
|:-----------|------------:|:------------:|
| 左寄せ | 右寄せ | 中央寄せ |</p>
<p>すごい!</p>

テーブルが変換されていないので少し調べる。どうやらエクステンション指定して実行しないとならないみたい。オフィシャルでサポートされているエクステンションは、実行時に指定するだけでコンバートしてくれるみたい。テーブルはオフィシャルに含まれている。その他サードパーティもたくさんある模様。

呼び出しのところにエクステンションを持たせる。

md = markdown.Markdown(extensions=['tables'])
print(md.convert(sample_text))

実行する。

<h1>h1の文字が出てくると嬉しい</h1>
<hr />
<h2>h2の文字はでてくるだろう</h2>
<ul>
<li>リスト1</li>
<li>リスト2</li>
<li>リスト3</li>
</ul>
<blockquote>
<p>引用してくれ</p>
</blockquote>
<p>本文で <strong>太字にもなるし</strong><em>斜体にもなるはず</em></p>
<p><code>まさかコードも入れられるんですか?
if (!lie) {
    return true;
}</code></p>
<table>
<thead>
<tr>
<th align="left">header1</th>
<th align="right">header2</th>
<th align="center">header3</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left">左寄せ</td>
<td align="right">右寄せ</td>
<td align="center">中央寄せ</td>
</tr>
</tbody>
</table>
<p>すごい!</p>

すごい!