# -*- 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)
自动删除TXT文件中多余的空行,然后将章节突出出来。用于清理txt小说文本。基于python
最新推荐文章于 2024-07-29 02:36:05 发布