[python小工具]小说分割器
生活随笔
收集整理的這篇文章主要介紹了
[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_namepath_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 folderif not os.path.exists(target_path):os.mkdir(target_path)# open the source fileinput = open(source_path, 'r',encoding='utf-8')sec_count = 0sec_cache = []title_cache=[]output = open('%s\\前言.txt' % (target_path), 'w',encoding='utf-8')preface_title = '%s 前言' % novel_titleoutput.writelines(preface_title)for line in input:# is a chapter's title?#if line.strip() == '': #去掉空行# passif 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 sectionoutput = 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 menuoutput = open('%s\\目錄.txt' % (target_path), 'w',encoding='utf-8')menu_head = '%s 目錄' % novel_titleoutput.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()?
總結
以上是生活随笔為你收集整理的[python小工具]小说分割器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 智能集群理论优化控制_探索群体智能的奥妙
- 下一篇: C# ListView控件用法