LoginSignup
0
4

More than 1 year has passed since last update.

Pythonでフォルダ内のMarkdown文書をHTMLに変換する

Last updated at Posted at 2023-04-10

Markdown形式で書いた記事をWebページで公開したい。

  1. まず、markdown形式の記事を整理して、フォルダを作成する。
    名前をmd-folderとする。

  2. 次に、空のフォルダ(html-folder)を作成する。
    md-folder内のmarkdownファイルをhtmlファイルに変換して、変換後のファイルをhtml-folderに上書きしたい。

  3. <webサイトを作りたい。webサイトの構想>
    html-folderを、Webページの左側にファイルツリーにして表示するつもりである。
    markdown形式の記事を今後もWebページに追加していく予定である。
    過去に書いた記事を書き換えることもある。
    その度、markdown-folder更新→html-folder更新→ファイルツリー更新とする。
    メインページはその都度書き換えたくないので、メインページにファイルツリーのhtmlファイルを読み込む。
    ファイルツリーのhtmlファイルを、記事を追加する度に更新する形にする。

  4. chatGPTに「"mdフォルダ"内を再帰的に探索してmarkdownのファイルを全てhtmlのファイルに変換する。"htmlフォルダ"に上書きして書き込むpythonのコードを書いて欲しい。」
    とお願いする。

markdownライブラリがインストールされていることを確認

インストールされていない場合は、以下のコマンドでインストール。

pip install markdown

Pythonスクリプトを作成。

md2html.py:

import os
import glob
import markdown

def convert_md_to_html(input_path, output_path):
    with open(input_path, 'r', encoding='utf-8') as md_file:
        md_text = md_file.read()
        html = markdown.markdown(md_text)

    with open(output_path, 'w', encoding='utf-8') as html_file:
        html_file.write(html)

def main():
    input_folder = 'md-folder'
    output_folder = 'html-folder'

    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    for md_file_path in glob.glob(f'{input_folder}/**/*.md', recursive=True):
        relative_path = os.path.relpath(md_file_path, input_folder)
        output_path = os.path.splitext(os.path.join(output_folder, relative_path))[0] + '.html'
        output_dir = os.path.dirname(output_path)

        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        convert_md_to_html(md_file_path, output_path)
        print(f"変換完了: {md_file_path} -> {output_path}")

if __name__ == '__main__':
    main()

このスクリプトを実行すると、md-folder内のすべてのMarkdownファイルが再帰的に探索され、それらがHTMLに変換され、htmlフォルダ内に同じディレクトリ構造で上書きされる。
html-folderが存在しない場合は、スクリプトが自動的に作成する。

1. convert_md_to_html 関数の解説

この関数は、入力ファイル(Markdownファイル)と出力ファイル(HTMLファイル)のパスを引数に取り、入力ファイルをHTMLに変換して出力ファイルに保存する。

def convert_md_to_html(input_path, output_path):
    # Markdownファイルを読み込む
    with open(input_path, 'r', encoding='utf-8') as md_file:
        md_text = md_file.read()
        # MarkdownをHTMLに変換
        html = markdown.markdown(md_text, extensions=['fenced_code'])

    # HTMLファイルを作成・書き込む
    with open(output_path, 'w', encoding='utf-8') as html_file:
        html_file.write( ... )

main関数の解説

この関数は、入力フォルダ内のすべてのMarkdownファイルを検索し、それぞれのファイルに対してconvert_md_to_html関数を呼び出してHTMLに変換し、出力フォルダに保存する。

def main():
    input_folder = 'md-folder'
    output_folder = 'html-folder'

    # 出力フォルダが存在しなければ作成
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 入力フォルダ内のすべてのMarkdownファイルを検索
    for md_file_path in glob.glob(f'{input_folder}/**/*.md', recursive=True):
        # 出力ファイルの相対パスを計算
        relative_path = os.path.relpath(md_file_path, input_folder)
        output_path = os.path.splitext(os.path.join(output_folder, relative_path))[0] + '.html'
        output_dir = os.path.dirname(output_path)

        # 出力フォルダが存在しなければ作成
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        # MarkdownファイルをHTMLファイルに変換
        convert_md_to_html(md_file_path, output_path)

注意点

プログラムを表示したいときmarkdownでは、バッククォーテーション3つで囲む。
始まりのバッククォーテーション3つの右に"zsh"や"python"など言語名を入れる。
"zsh"を入れていると正常にhtml変換されないので、"bash"に書き換える必要がある。

0
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
4