让ai写了一个小说去标题的脚本,试了好多回终于能用了,分享出来给大家瞧瞧。
import re
import os
def remove_chapter_titles(input_file, output_file=None):
"""
移除TXT文件中的章节标题
参数:
input_file: 输入的TXT文件路径
output_file: 输出的TXT文件路径,默认为在原文件名后加"_无标题"
"""
# 如果未指定输出文件,则在原文件名后添加"_无标题"
if output_file is None:
file_name, file_ext = os.path.splitext(input_file)
output_file = f"{file_name}_无标题{file_ext}"
# 章节标题的正则表达式模式
# 匹配"第X章"格式,X可以是数字、中文数字等
chapter_pattern = re.compile(r'^第[\d零一二三四五六七八九十百千万]+章.*$', re.IGNORECASE)
try:
with open(input_file, 'r', encoding='utf-8') as f_in, \
open(output_file, 'w', encoding='utf-8') as f_out:
removed_count = 0 # 统计移除的标题数量
for line in f_in:
# 检查是否是章节标题
if chapter_pattern.match(line.strip()):
removed_count += 1
continue # 跳过章节标题行
# 不是标题行则写入输出文件
f_out.write(line)
print(f"处理完成!")
print(f"已移除 {removed_count} 个章节标题")
print(f"处理后的文件已保存至: {output_file}")
except FileNotFoundError:
print(f"错误:找不到文件 '{input_file}'")
except Exception as e:
print(f"处理过程中发生错误:{str(e)}")
if __name__ == "__main__":
# 请将下面的路径替换为你的小说文件路径
novel_file_path = "C:\\Users\\Administrator\\Desktop\\小说.txt" # 输入你的小说文件名或路径
# 调用函数处理文件
remove_chapter_titles(novel_file_path)

