建議檔名: 批次txt→html.py
Sigil 的【增加已存在的檔案】功能可以滙入 txt 檔案,
不過是作為附檔,無法直接作為電子書頁面觀看
為解決這個小困擾,就把【txt檔】轉換為【html檔】
經測試 Sigil 對匯入 html檔 的處理流程
找出最簡約的【txt檔】轉【html檔】的條件
就是段落前後加上 <p>及</p>,保持原有排版
【<p>就像這樣</p>】
副作用:
轉換為 *.html 後,在桌機瀏覽檔案時點擊可選擇由
【網路瀏覽器】開啟,就像一般最陽春的網頁。
不過手機上的【小說瀏覽器】不知為何不支援網頁檔
(感覺像不搶【網路瀏覽器】的生意)
程式碼:
(複製以下文字,貼入純文字檔中,存檔後將副檔名設定為 .py)
import os
def split_pages(lines, page_size=20):
for i in range(0, len(lines), page_size):
yield lines[i:i+page_size]
def convert_txt_to_html_wrapped(input_folder, output_folder):
if not os.path.exists(output_folder):
os.makedirs(output_folder)
txt_files = [f for f in os.listdir(input_folder) if f.lower().endswith('.txt')]
if not txt_files:
print("❌ 找不到任何 .txt 檔案。")
return
preview_list = []
for txt_file in txt_files:
html_file = os.path.splitext(txt_file)[0] + ".html"
preview_list.append(f"{txt_file} → {html_file}")
# 預覽對照表(分頁方式)
print("📄 預覽將轉換下列檔案(按 Enter 進行下一頁):\n")
for page in split_pages(preview_list, page_size=20):
for line in page:
print(line)
input("—— 按 Enter 查看下一頁 ——")
input("\n✅ 確認後請按 Enter 開始轉換...\n")
for txt_file in txt_files:
input_path = os.path.join(input_folder, txt_file)
output_path = os.path.join(output_folder, os.path.splitext(txt_file)[0] + ".html")
with open(input_path, "r", encoding="utf-8") as infile:
lines = infile.readlines()
wrapped_lines = []
for line in lines:
# 保留原本的所有空白與換行,但用 <P> 包裹
stripped_line = line.rstrip("\n\r")
if stripped_line.strip() == "":
continue # 跳過空白行
wrapped_line = f"<P>{stripped_line}</P>"
wrapped_lines.append(wrapped_line)
with open(output_path, "w", encoding="utf-8") as outfile:
outfile.write("\n".join(wrapped_lines))
print(f"\n✅ 全部轉換完成!HTML 檔案已輸出至:{output_folder}")
# 使用範例
if __name__ == "__main__":
input_folder = input("請輸入 TXT 檔所在的資料夾路徑:").strip('"')
output_folder = os.path.join(input_folder, "輸出結果")
convert_txt_to_html_wrapped(input_folder, output_folder)