掲示板<24>2025/12/31
from=TOZ

Pythonを利用①「total_process.py」

いろいろな動作をするプログラムをつくることのできるプログラム言語のPythonがLinuxMintでは 端末ですぐに使えるので、Pathに気をつけながら作成してみた。 toz山荘のサイト更新に利用するために、20回分のhtmlが書かれているgot21.htmlを例に紹介する。 got21.htmlからバラバラの20個のhtmlファイルを作る「total_process.py」をGeminiに教わ りながら作成した。
import re
import os

# --- 関数の定義(先に準備します) ---
def save_final_html(num, body_list, top, last):
    """ファイルを連結し、最後の置換をして保存する関数"""
    body_text = "".join(body_list)
    
    # 3. 仕上げの置換 (multireplace.pyの機能)
    target = f'sec{num}"></a>'
    final_body = body_text.replace(target, '<h2>')
    
    output_filename = f"{num}.html"
    with open(output_filename, "w", encoding="utf-8") as f:
        f.write(top + "\n" + final_body + "\n" + last)
    print(f"作成完了: {output_filename}")

# --- メイン処理 ---
# 設定
input_file = "got21.html"
top_file = "top.html"
last_file = "last.html"
start_phrase = "START_HERE" 
end_phrase = "END_HERE"

print("1. 前処理を開始します...")
with open(input_file, "r", encoding="utf-8") as f:
    lines = f.readlines()

processed_lines = []
is_skipping = False
for line in lines:
    if start_phrase in line:
        is_skipping = True
        continue
    if end_phrase in line:
        is_skipping = False
        continue
    if not is_skipping:
        new_line = line.replace('<h2><a name="', 'sec')
        processed_lines.append(new_line)

print("2. 分割と連結を開始します...")
with open(top_file, "r", encoding="utf-8") as f:
    top_html = f.read()
with open(last_file, "r", encoding="utf-8") as f:
    last_html = f.read()

current_sec_content = []
current_num = None

for line in processed_lines:
    match = re.match(r'^(sec\d+)', line)
    if match:
        # すでに前のセクションがあれば保存
        if current_num and current_sec_content:
            save_final_html(current_num, current_sec_content,
 top_html, last_html)
        
        # 新しいセクション準備
        current_num = match.group(1).replace("sec", "")
        current_sec_content = [line]
    else:
        if current_num:
            current_sec_content.append(line)

# 最後のセクションを保存
if current_num and current_sec_content:
    save_final_html(current_num, current_sec_content,
 top_html, last_html)

print("\n--- すべての工程が完了しました! ---")
【要注意】
HTMLでタブに使う<と>は原則
半角ですが、ここでは山括弧<や
山括弧>を半角にすると見えなく
なるので、ここでは全角表示して
いますので、コピー後は半角に直
してご利用ください。


これで実行(Enter)すれば自動作成される。

← 一覧へ戻る