写本文的思路很简单:
自己是一个小说迷,有时候就想着能不能把一个整本的小说给分割成一个个单章存在的文本文件
之前也在网上找到过别人写的软件,然后最近突然想到,能否用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()