日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

[python小工具]小说分割器

發(fā)布時間:2023/12/10 python 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [python小工具]小说分割器 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

寫本文的思路很簡單:

自己是一個小說迷,有時候就想著能不能把一個整本的小說給分割成一個個單章存在的文本文件

之前也在網(wǎng)上找到過別人寫的軟件,然后最近突然想到,能否用python實現(xiàn)一下

?

其實有了這個目標(biāo),實現(xiàn)起來很簡單:

最核心的就是匹配關(guān)鍵字符串

整體代碼如下

# -*- 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小說分割轉(zhuǎn)換成單個章節(jié)文件 文件名字以章節(jié)命名 本文運行在python3上面, 處理小說的時候,需要將小說的格式以utf-8保存 (處理以ANSI編碼格式的txt文本會出現(xiàn)錯誤) '''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)#章節(jié)名字當(dāng)文件名字時,不能有特殊符號# 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()

?

總結(jié)

以上是生活随笔為你收集整理的[python小工具]小说分割器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。