建議檔名: 單檔章節間插入分隔線.py
這是試製品,針對單一TXT檔【完本小說】
在各個章節名稱前插入分隔線並添加序列數
這些分隔標記是預備用來作為
把【完本小說】依章節精確分割的錨點
程式碼具有基本的章節判別準則
也可以參考外部的章節列表【目錄.txt】來精準辨識
程式碼:
(複製以下文字,貼入純文字檔中,存檔後將副檔名設定為 .py)
import os
import re
def extract_chapter_titles(toc_file):
"""
從目錄文件提取章節標題。
假設格式為:章節標題 + 日期時間,忽略非必要段落。
"""
titles = []
if toc_file and os.path.isfile(toc_file):
with open(toc_file, "r", encoding="utf-8") as file:
for line in file:
# 偵測章節標題,忽略多餘行(如最初へ、前へ等)
match = re.match(r"^(第[一二三四五六七八九十百千]+話\s+.*?)\s+\d{4}/\d{2}/\d{2}", line)
if match:
titles.append(match.group(1).strip())
return titles
def insert_dividers(input_folder, output_folder, toc_file):
"""
在檔案中插入章節分隔標記(****** + 四碼全形序號)。
"""
if not os.path.exists(output_folder):
os.makedirs(output_folder)
toc_titles = extract_chapter_titles(toc_file) if toc_file else None
for file_name in os.listdir(input_folder):
if file_name.endswith(".txt"):
input_file = os.path.join(input_folder, file_name)
output_file = os.path.join(output_folder, file_name)
with open(input_file, "r", encoding="utf-8") as file:
lines = file.readlines()
chapter_counter = 1
output_lines = []
for line in lines:
stripped_line = line.strip()
# 如果是章節標題,插入分隔標記
if toc_titles and stripped_line in toc_titles:
divider = f"****** {chapter_counter:04d}"
output_lines.append(divider)
chapter_counter += 1
output_lines.append(line.rstrip())
with open(output_file, "w", encoding="utf-8") as file:
file.write("\n".join(output_lines) + "\n")
def main():
print("章節分隔標記插入工具")
input_folder = input("請輸入包含 TXT 文件的資料夾路徑:").strip()
output_folder = input("請輸入輸出結果的資料夾路徑:").strip()
toc_file = input("若有目錄文件,請輸入其路徑(可按 Enter 跳過):").strip()
if not os.path.isdir(input_folder):
print(f"輸入的資料夾路徑無效:{input_folder}")
return
insert_dividers(input_folder, output_folder, toc_file if toc_file else None)
print(f"處理完成!結果已存放於:{output_folder}")
if __name__ == "__main__":
main()
# Insert Dividers Tool
# Version: 2025/01/25 20:45