自动删除TXT文件中多余的空行,然后将章节突出出来。用于清理txt小说文本。基于python

# -*- coding: utf-8 -*-
"""
读取存在空行的文件,删除其中的空行。
默认直接读取py文件同级目录下全部txt文件,并自动转换。也可以手动设置待转换文件夹。
"""

import os
def 清除空行(待清除文件):
    待清除文件=待清除文件.replace('.txt','')+'.txt'
    清除后文件名=待清除文件.replace('.txt','')+'_已清除.txt'
    with open(待清除文件,'r',encoding = 'utf-8') as fr,open(清除后文件名,'w',encoding = 'utf-8') as fd:
        for text in fr.readlines():
            # print('测试:%s' % text[1])
            # os._exit()
            if text.split():
                if (text[0]=='第',text[1]=='第') and ('章' in text[:10] or '节' in text[:10]) and len(text)<100:
                    fd.write('\n')
                    fd.write(text)
                    fd.write('\n')
                else:
                    fd.write(text)
            # print('输出成功....')
def find_file(path, ext, file_list=[]):
    dir = os.listdir(path)
    for i in dir:
        i = os.path.join(path, i)
        if os.path.isdir(i):
            find_file(i, ext, file_list)
        else:
            if ext == os.path.splitext(i)[1]:
                file_list.append(i)
    return file_list



#获取当前py文件所在路径
dir_path=os.path.split(os.path.realpath(__file__))[0]
# dir_path = r'C:\Users\abc\Downloads\Documents'#手动设置批量转换文件夹
ext = ".txt"
待清除列表_list = find_file(dir_path, ext)
# print(待清除列表_list)

for file in 待清除列表_list:   
    清除空行(file)
    # print(file.replace('.txt','_已清除.txt'))
    os.remove(file)
    os.rename(file.replace('.txt','_已清除.txt'),file)
    print("处理完毕:%s" % file)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值