关于#python#的问题:批量删除小说内容

就是如何使用Python批量消除小说的标题什么的,就比如第一章第二章,怎么才能一次性消除,我有几千本txt格式的需要消除,我完全不会Python,还没开始学,希望能说的详细点

你题目的解答代码如下:

# -*- coding: utf-8 -*-
import re
import os
import chardet
# 检测文件编码函数
def detectCode(path):
    with open(path, 'rb') as file:
        data = file.read(20000)
        dicts = chardet.detect(data)
    return dicts["encoding"]

# 替换文本函数
def textreplace(text):
    return re.sub(r'^\s*第.+章.+$\n','',text, flags=re.M)

# 读取"E:\xxx"文件夹下所有txt文件
path=r"E:\xxx"
for root, dirs, files in os.walk(path):
    for fn in files:
        if fn.endswith(".txt"):  # 判断是txt文件
            file_path = os.path.join(root,fn)  #拼接成完整文件路径
            print("文件:",file_path)
            encoding = detectCode(file_path) # 检测文件编码
            if encoding=="GB2312":
                encoding = "GBK"
            # 读取文件中
            with open(file_path, 'r', encoding=encoding) as fileObj:
                text = fileObj.read()
            text = textreplace(text)  #替换文本
            # print(text)
            # 回写txt文件
            with open(file_path, 'w', encoding=encoding) as fileObj:
                fileObj.write(text)

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img

主要还是找到标题的特点,找到他的规律进行删除

你可以参考下这篇文章:用python爬取小说章节内容