admin管理员组文章数量:1660065
# -*- 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 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dianzi/1729844967a1215022.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论