Python)青空文庫をスマホで機内モード(オフライン)で縦書きで読むためにXHTMLを変換するWindowsアプリを作成。

2025-11-19 · ホームページ、Web作成 スマホ・タブレット 文学

飛行機の機内で、スマホで青空文庫を縦書きで読みたい。

青空文庫 Aozora Bunkowww.aozora.gr.jp

アクセスランキングwww.aozora.gr.jp

スマホの青空文庫ビューアーアプリはたくさんあるが、機能が多すぎてかえって使いづらい。オフラインに対応していないものもある。広告が表示されて煩わしいものが多い。

シンプルにスマホでオフラインで青空文庫を縦書きで読みたい。

青空文庫のXHTMLファイルを縦書き用に変換するWindowsアプリをPythonで作成した。

≪ ■ 手順 ≫
  1. 青空文庫から、PCでXHTMLをダウンロードする。

  2. 今回作成したアプリで、XHTMLファイルを縦書き用に変換する。フォルダー指定で複数ファイルを一括変換する。

  3. PCからスマホにXHTML縦書きファイルをコピーする。
  4. スマホで、ブラウザでXHTML縦書きファイルを開く。

【スマホファイルマネージャー画面例】

【スマホXHTML縦書きファイル表示サンプル】

【PCでのXHTML縦書きファイル表示サンプル】

≪ ■ Pythonアプリ:主な処理 ≫
≪ ■ Pythonアプリ:ソース ≫
import os
import re
import tkinter as tk
from tkinter import filedialog, messagebox

# ---------------------------------------------------------
# HTML から charset を判定
# ---------------------------------------------------------
def detect_charset(html_bytes):
    encodings = ["utf-8", "shift_jis", "euc-jp", "cp932"]

    for enc in encodings:
        try:
            text = html_bytes.decode(enc)
            if re.search(r'<meta[^>]*charset=["\']?([a-zA-Z0-9\-\_]+)', text, re.I):
                return enc
        except:
            pass

    return "utf-8"

# ---------------------------------------------------------
# HTML1件処理
# ---------------------------------------------------------
def process_html(path, head_html_original):
    with open(path, "rb") as f:
        raw = f.read()

    enc = detect_charset(raw)

    try:
        text = raw.decode(enc)
    except:
        text = raw.decode("cp932", errors="ignore")
        enc = "cp932"

    original_text = text

    # ---------------------------
    # 元の <title> を抽出
    # ---------------------------
    title_match = re.search(r'<title[^>]*>(.*?)</title>', text, flags=re.I | re.S)
    if title_match:
        original_title = title_match.group(0)
    else:
        original_title = None

    # ---------------------------
    # style="..." の削除
    # ---------------------------
    text = re.sub(r'\s*style=["\'].*?["\']', '', text, flags=re.I | re.S)

    # ---------------------------
    # <img ~> を削除
    # ---------------------------
    text = re.sub(r"<img[^>]*>", "", text, flags=re.I)

    # ---------------------------
    # <a href="xxx"> の変換
    # ---------------------------
    def fix_href(match):
        href = match.group(1)
        if "#" in href:
            return f'<a href="#{href.split("#",1)[1]}">'
        else:
            return f'<a href="{href}">'

    text = re.sub(r'<a\s+href=["\'](.*?)["\']>', fix_href, text, flags=re.I)

    # -----------------------------------------------------
    #   <div class="notation_notes"> 〜 </body の直前の </div> を削除
    # -----------------------------------------------------
    text = re.sub(
        r'<div[^>]*class=["\']notation_notes["\'][^>]*>.*?</div>',
        '',
        text,
        flags=re.I | re.S
    )

    # -----------------------------------------------------
    # id="card" を持つ div を丸ごと削除
    # -----------------------------------------------------
    text = re.sub(
        r'<div[^>]*id=["\']card["\'][^>]*>.*?</div>',
        '',
        text,
        flags=re.I | re.S
    )

    # -----------------------------------------------------
    # head.html を基に head を置き換え(title は元のまま)
    # -----------------------------------------------------
    head_html = head_html_original

    # head.html 内の title を削除
    head_html = re.sub(r'<title[^>]*>.*?</title>', '', head_html, flags=re.I | re.S)

    # 元タイトルを head の直後に挿入
    if original_title:
        head_html = re.sub(
            r'<head[^>]*>',
            lambda m: m.group(0) + "\n    " + original_title,
            head_html,
            count=1,
            flags=re.I
        )

    # head 差し替え
    try:
        text = re.sub(
            r'<head[^>]*>.*?</head>',
            head_html,
            text,
            flags=re.I | re.S
        )
    except:
        text = original_text

    # -----------------------------------------------------
    # <body> 以降の空行削除
    # -----------------------------------------------------
    lines = text.splitlines()
    cleaned = []
    in_body = False

    for line in lines:
        if "<body" in line.lower():
            in_body = True
            cleaned.append(line)
            continue

        if in_body:
            if line.strip() == "":
                continue

        cleaned.append(line)

    text = "\n".join(cleaned)

    # ---------------------------
    # 保存
    # ---------------------------
    with open(path, "w", encoding=enc, errors="ignore") as f:
        f.write(text)


# ---------------------------------------------------------
# フォルダ処理
# ---------------------------------------------------------
def convert_folder(folder):
    head_path = os.path.join(os.path.dirname(__file__), "head.html")

    if not os.path.exists(head_path):
        messagebox.showerror("エラー", "head.html がアプリのフォルダにありません。")
        return

    with open(head_path, "r", encoding="shift_jis", errors="ignore") as f:
        head_html = f.read()

    count = 0
    for root, dirs, files in os.walk(folder):
        for file in files:
            if file.lower().endswith((".html", ".htm", ".xhtml")):
                process_html(os.path.join(root, file), head_html)
                count += 1

    messagebox.showinfo("完了", f"{count} 件のHTML/XHTMLを処理しました。")


# ---------------------------------------------------------
# GUI
# ---------------------------------------------------------
def select_folder():
    folder = filedialog.askdirectory()
    if folder:
        folder_var.set(folder)


def run_convert():
    folder = folder_var.get()
    if not folder:
        messagebox.showerror("エラー", "フォルダーを選択してください。")
        return
    convert_folder(folder)


# ---------------------------------------------------------
# メインウィンドウ
# ---------------------------------------------------------
root = tk.Tk()
root.title("HTML 縦書き一括変換ツール")
root.geometry("500x180")

folder_var = tk.StringVar()

tk.Label(root, text="処理するフォルダーを選択してください:").pack(pady=10)

frame = tk.Frame(root)
frame.pack()

tk.Entry(frame, textvariable=folder_var, width=50).pack(side=tk.LEFT, padx=5)
tk.Button(frame, text="フォルダー選択", command=select_folder).pack(side=tk.LEFT)

tk.Button(root, text="変換実行", command=run_convert, width=20).pack(pady=20)

root.mainloop()

スマホアプリ「読書尚友 Lite」を使えば、作成した縦書きHTMLをページ単位で読むことが出来る。(↓)

縦書きHTMLファイルは、スマホアプリ「読書尚友 Lite」でページ割りして読める。(青空文庫)先程、青空文庫XHTMLファイルを縦書きに変換するWindowsアプリを作成した。 作成したHTMLファイルは、スマホブラウザで縦書きで読め…晴歩雨描 ·

Windows)Python).htmlファイルと「_files」フォルダーのリンク(コネクテッド・ファイル機能)を外すツール作成。フォルダー名一括変換アプリ。青空文庫HTMLなど。青空文庫HTMLなど、Windowsでウェブページを保存した際、 .htmlファイル と 「_files」フォルダー がセットになり、片方を…晴歩雨描 ·

晴歩雨描:記事一覧ok2nd.github.io

Claude)Python)「写真スポット編集ツール」Windowsアプリ作成。シミ消し、オブジェクト除去に使える。スポット修正+コピー修正。ICCプロファイル維持。以前に、「写真オブジェクト除去」Windowsアプリを作成した。 これは、写真の一部をスポット的に編集するアプリ。 これに加えて、クローンコ…晴歩雨描 ·

Claude)Python)透過画像作成Windowsアプリ作成。Pythonで「透過画像作成」Windowsアプリ作成。画像の白に近い色を透過にする。元データはJPEGまたはPNG。白の範囲は指定できる。…晴歩雨描 ·

JavaScript版「ブラウザで縦書き表示&印刷」作成。「window.opener」を使えば、親子ウインドウ間のデータ受け渡しは簡単。以前、「ブラウザでテキスト縦書き表示」するページを作成した。 この時作成したのは、サーバーサイドでPHPで処理して縦書きページを表示する方式…晴歩雨描 ·

Gemini Storybook)絵本作成。オオソリハシシギの長距離の渡りの物語。昨日から、 Gemini Storybook で絵本を4本作った。 また、新しい絵本を作成。 オオソリハシシギの長距離の渡りの物語。 生後5…晴歩雨描 ·

Gemini Storybookで絵本を作った。日本の平安時代の清少納言の枕草子のような世界観で。Google Geminiに、絵本生成アプリ「 Storybook 」が出来たらしい。 10ページの絵本が簡単に出来てしまう。 試してみた。…晴歩雨描 ·

AI清少納言の未発表随筆を、毛筆フォント「英椎行書」で縦書きで書いて、和紙テクスチャーと合成してPDFに。昨日、生成AIのChatGPT「 GPT-5 」を使って、 AI「清少納言」 に、未発表の随筆「未聞の草子:あはれをかしの記」を発表してもら…晴歩雨描 ·

AI詩人「萩原朔太郎、北原白秋、与謝野晶子、金子みすゞ」に、短歌を詠んでもらう。Google Geminiで。Google Geminiに、昔の詩人になったつもりで、短歌を詠んでもらった。 お題を変えて、いくつか試した。 それぞれの作家の作風を理解し…晴歩雨描 ·

清少納言に紫式部に対してどう思っているか聞いてみた。ChatGPT、Gemini、Copilot、Perplexity、Claude。ネット上に面白い記事があった。 『Google Geminiを使って紫式部と散歩しながら語彙力バトルをしてみた|斉藤ナミ』 そこで、AIに次…晴歩雨描 ·