您当前的位置:首页 > 计算机 > 编程开发 > Python

小说自动分割脚本 把整本小说每5000字符自动分割成一本新的txt格式的脚本

时间:09-09来源:作者:点击数:

把整本小说每5000字符自动分割成一本新的txt格式的脚本

def split_novel(source_file, chars_per_file=5000):
        try:
            # 读取源文件内容
            with open(source_file, 'r', encoding='utf-8') as f:
                content = f.read()
             
            total_length = len(content)
            total_files = (total_length + chars_per_file - 1) // chars_per_file  # 计算需要的文件总数
            print(f"小说总长度: {total_length} 字符")
            print(f"将分割为 {total_files} 个文件,每个文件约 {chars_per_file} 字符")
             
            # 分割并保存为多个文件
            for i in range(total_files):
                start = i * chars_per_file
                end = start + chars_per_file
                part_content = content[start:end]
                 
                # 生成文件名,如 "novel_part_001.txt"
                output_file = f"{source_file.split('.')[0]}_part_{i+1:03d}.txt"
                 
                with open(output_file, 'w', encoding='utf-8') as f:
                    f.write(part_content)
                 
                print(f"已生成: {output_file},字符数: {len(part_content)}")
                 
        except FileNotFoundError:
            print(f"错误: 找不到文件 '{source_file}'")
        except Exception as e:
            print(f"发生错误: {str(e)}")
 
    if __name__ == "__main__":
        # D:/阿里云/video/视频/第一个小时/第五卷/小说_无标题.txt
        novel_file = "your_novel.txt"
        # 调用函数进行分割,默认每5000字符一个文件
        split_novel(novel_file)

 

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐