[python小工具]小说分割器

写本文的思路很简单:

自己是一个小说迷,有时候就想着能不能把一个整本的小说给分割成一个个单章存在的文本文件

之前也在网上找到过别人写的软件,然后最近突然想到,能否用python实现一下

 

其实有了这个目标,实现起来很简单:

最核心的就是匹配关键字符串

整体代码如下


# -*- coding: utf-8 -*-
# @Date     : 2018-11-02 17:38:53
# @Author   : Jimy_Fengqi (jmps515@163.com)
# @Link     : https://blog.csdn.net/qiqiyingse
# @Version  : V1.0

'''
将txt小说分割转换成单个章节文件
文件名字以章节命名
本文运行在python3上面,
处理小说的时候,需要将小说的格式以utf-8保存
(处理以ANSI编码格式的txt文本会出现错误)
'''

import re
import os
import sys

# txt book's path.
novel_name='' #小说名字
source_path = os.getcwd()+'\\'+novel_name

path_pieces = os.path.split(source_path)
novel_title = re.sub(r'(\..*$)|($)', '', path_pieces[1])
target_path = '%s\\%s' % (path_pieces[0], novel_title)#小说分章目录
section_re = re.compile(r'^\s*第.+章\s+.*$')


# entry of the script
def main():
    # create the output folder
    if not os.path.exists(target_path):
        os.mkdir(target_path)

    # open the source file
    input = open(source_path, 'r',encoding='utf-8')

    sec_count = 0
    sec_cache = []
    title_cache=[]

    output = open('%s\\前言.txt' % (target_path), 'w',encoding='utf-8')
    preface_title = '%s 前言' % novel_title
    output.writelines(preface_title)

        
    for line in input:
        # is a chapter's title?
        #if line.strip() == '':  #去掉空行
        #    pass
        if re.match(section_re, line):
            line = re.sub(r'\s+', ' ', line)
            print ('converting %s...' % line)
    
            output.writelines(sec_cache)
            output.flush()
            output.close()
            sec_cache = []
            sec_count += 1
            #chapter_name=re.sub('(~|!+|\(+|\)+|~+|\(+|\)+|(+|!+)','_',line)
            chapter_name=re.sub('(~+|\*+|\,+|\?+|\,+|\?+)','_',line)#章节名字当文件名字时,不能有特殊符号


            # create a new section
            output = open('%s\\%s.txt' % (target_path, chapter_name), 'w',encoding='utf-8')
            output.writelines(line)
            title_cache.append(line+'\n')
        else:
            sec_cache.append(line)
            
    output.writelines(sec_cache)
    output.flush()
    output.close()
    sec_cache = []

    # write the menu
    output = open('%s\\目录.txt' % (target_path), 'w',encoding='utf-8')
    menu_head = '%s 目录' % novel_title
    output.writelines(menu_head)
    output.writelines(title_cache)
    output.flush()
    output.close()
    inx_cache = []
    
    print ('completed. %d chapter(s) in total.' % sec_count)

if __name__ == '__main__':
    main()

 

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值