说明:
我的计划是提取飞卢小说,然后切割,然后训练批判思维
step1:
import os
import requests
from bs4 import BeautifulSoup
def generate_filename(index):
"""生成两位字母组合文件名,按aa,ab...zz顺序"""
if index < 0 or index >= 26 * 26:
raise ValueError("Index out of range (0-675)")
first = index // 26
second = index % 26
return f"{chr(97 + first)}{chr(97 + second)}.txt"
def save_novel_content(start_page, end_page, novel_id, save_dir):
"""
保存小说内容到本地
参数:
start_page: 起始页码
end_page: 结束页码(包含)
novel_id: 小说ID(如示例中的1479359)
save_dir: 保存路径
"""
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}
if not os.path.exists(save_dir):
os.makedirs(save_dir)
for i in range(start_page, end_page + 1):
url = f"https://wap.faloo.com/{novel_id}_{i}.html"
try:
# 获取网页内容
response = requests.get(url, headers=headers)
response.encoding = 'gbk'
soup = BeautifulSoup(response.text, 'html.parser')
# 提取原始HTML内容(保留标签)
content_div = soup.find('div', class_='nodeContent')
content = str(content_div) if content_div else ""
# 生成文件名并保存
filename = generate_filename(i - start_page)
filepath = os.path.join(save_dir, filename)
with open(filepath, 'w', encoding='utf-8') as f:
f.write(content)
print(f"已保存第{i}页内容到:{filepath}")
except Exception as e:
print(f"处理第{i}页时出错:{str(e)}")
# 使用示例
if __name__ == "__main__":
save_path = r"D:\Users\wangrusheng\Downloads\dce"
novel_id = 1479359
start_page = 1
end_page = 40
save_novel_content(
start_page=start_page,
end_page=end_page,
novel_id=novel_id,
save_dir=save_path
)
====分割线
import os
import re
def merge_txt_files(input_dir, output_file):
"""
将指定目录下所有符合 aa,ab,...,zz 命名规则的txt文件按顺序合并到新文件。
:param input_dir: 输入目录路径
:param output_file: 合并后的输出文件路径
:return: 合并的文件数量
"""
# 获取目录下所有文件
all_files = os.listdir(input_dir)
# 匹配两个字母组成的txt文件名(不区分大小写)
pattern = re.compile(r'^[a-zA-Z]{2}\.txt$', re.IGNORECASE)
matched_files = []
for filename in all_files:
if pattern.match(filename):
basename = os.path.splitext(filename)[0].lower()
if len(basename) == 2 and basename.isalpha():
matched_files.append((basename, filename))
# 按字母顺序排序
matched_files.sort(key=lambda x: x[0])
# 合并文件
with open(output_file, 'w', encoding='utf-8') as outfile:
for basename, filename in matched_files:
filepath = os.path.join(input_dir, filename)
try:
with open(filepath, 'r', encoding='utf-8') as infile:
outfile.write(infile.read())
# 可选:在每个文件内容后添加换行符
# outfile.write('\n')
except Exception as e:
print(f"处理文件 {filename} 时出错: {e}")
return len(matched_files)
# 示例用法
input_dir = r'D:\Users\wangrusheng\Downloads\dce'
output_file = r'D:\Users\wangrusheng\Downloads\dce\merged.txt'
count = merge_txt_files(input_dir, output_file)
print(f"成功合并 {count} 个文件。")
======分割线
import os
import math
def split_file_into_parts(file_path, num_parts=3, remark=""):
"""
将文件按固定份数分割成多个小文件
:param file_path: 原始文件路径
:param num_parts: 分割份数,默认3份
:param remark: 要添加到每个分割文件末尾的备注字符串。注意:对于二进制文件(非文本),添加文本备注会损坏文件。请谨慎使用!
"""
# 如果传入了备注,发出警告
if remark:
print(f"警告:您正在尝试向二进制分割文件添加文本备注‘{remark[:20]}...‘。这极有可能导致生成的文件损坏!")
# 获取文件名和目录
base_name = os.path.splitext(os.path.basename(file_path))[0]
dir_path = os.path.dirname(file_path) or '.' # 处理当前目录的情况
ext = os.path.splitext(file_path)[1] # 保留原扩展名
# 获取文件大小
file_size = os.path.getsize(file_path)
print(f"原文件大小: {file_size} 字节 ({file_size / 1024:.2f} KB)")
# 计算每部分的大小(向上取整,确保最后一部分包含剩余内容)
part_size = math.ceil(file_size / num_parts)
print(f"每部分大小: {part_size} 字节 ({part_size / 1024:.2f} KB)")
# 打开原始文件(二进制模式)
with open(file_path, 'rb') as f:
for part_num in range(1, num_parts + 1):
# 生成新文件名
output_file = os.path.join(dir_path, f"{base_name}_part{part_num}{ext}")
# 如果是最后一部分,读取剩余所有内容
if part_num == num_parts:
chunk = f.read() # 读取剩余所有内容
else:
# 读取指定大小的内容
chunk = f.read(part_size)
# 写入新文件
with open(output_file, 'wb') as out_file:
out_file.write(chunk)
# !!!危险操作:为二进制块添加文本备注(会破坏文件)
if remark:
out_file.write(f"\n{remark}".encode('utf-8'))
actual_size = len(chunk)
print(f"已创建: {output_file} (大小: {actual_size} 字节, {actual_size / 1024:.2f} KB)")
print(f"文件已成功分割成 {num_parts} 个部分!")
def split_text_file_into_parts(file_path, num_parts=3, encoding='utf-8', remark=""):
"""
将文本文件按固定份数分割成多个小文件(避免截断字符)
:param file_path: 原始文件路径
:param num_parts: 分割份数,默认3份
:param encoding: 文件编码,默认utf-8
:param remark: 要添加到每个分割文件末尾的备注字符串(可选)。
"""
# 获取文件名和目录
base_name = os.path.splitext(os.path.basename(file_path))[0]
dir_path = os.path.dirname(file_path) or '.' # 处理当前目录的情况
ext = os.path.splitext(file_path)[1] # 保留原扩展名
# 读取整个文件内容
with open(file_path, 'r', encoding=encoding) as f:
content = f.read()
file_size = len(content.encode(encoding))
print(f"原文件大小: {file_size} 字节 ({file_size / 1024:.2f} KB)")
print(f"总字符数: {len(content)}")
# 计算每部分的字符数(向上取整)
chars_per_part = math.ceil(len(content) / num_parts)
print(f"每部分字符数: {chars_per_part}")
for part_num in range(1, num_parts + 1):
# 计算当前部分的起始和结束位置
start_idx = (part_num - 1) * chars_per_part
end_idx = min(part_num * chars_per_part, len(content))
# 截取当前部分的内容
chunk = content[start_idx:end_idx]
# 生成新文件名
output_file = os.path.join(dir_path, f"{base_name}_part{part_num}{ext}")
# 写入新文件,并在末尾添加备注(如果提供了的话)
with open(output_file, 'w', encoding=encoding) as out_file:
out_file.write(chunk)
if remark: # 如果备注字符串非空,则添加
# 可以选择添加换行符分隔,避免与原内容连在一起
out_file.write(f"\n{remark}")
actual_size = len(chunk.encode(encoding))
actual_chars = len(chunk)
print(f"已创建: {output_file} (大小: {actual_size} 字节, 字符数: {actual_chars})")
print(f"文件已成功分割成 {num_parts} 个部分!")
# 执行分割操作
if __name__ == "__main__":
file_path = r"D:\Users\wangrusheng\Downloads\dce2\merged.txt"
print("=== 方法1: 二进制分割(适合任意文件类型) ===")
# 示例:不添加备注(因为zb.json是文本文件,用二进制模式分割并添加文本备注会损坏它)
split_file_into_parts(file_path, num_parts=10, remark="") # remark留空
print("\n=== 方法2: 文本分割(适合文本文件,避免乱码) ===")
# 示例:添加一条备注
# my_remark2 = "继续开始第二场辩论,模拟辩论,纯对话体, 话题是小学老师计划把上述材料用于帮助学生构建价值理性和社会伦理和启蒙思想 , (诘问者)苏格拉底vs小学老师(上述材料的狂热粉丝), 不低于1500字"
my_remark = "模拟辩论,纯对话体, 话题是小学老师计划把上述材料用于训练学生的批判性思维 , (诘问者)苏格拉底vs小学老师(上述材料的狂热粉丝), 不低于1500字"
split_text_file_into_parts(file_path, num_parts=10, encoding='utf-8', remark=my_remark)
3524

被折叠的 条评论
为什么被折叠?



