当前位置: 首页 > news >正文

python之---递归选择文件并生成新文件保持目录结构

python递归处理文件,保持被处理文件夹内的目录结构,生成处理结构的时候保持相同的目录结构

import json
import osdef run(data_dir, res_dir, clean_dir):for root, dirs, files in os.walk(data_dir):# 计算当前目录相对于源目录的相对路径rel_path = os.path.relpath(root, data_dir)# 在目标目录创建对应子目录res_subdir = os.path.join(res_dir, rel_path)os.makedirs(res_subdir, exist_ok=True)  # 自动创建不存在的目录clean_subdir = os.path.join(clean_dir, rel_path)os.makedirs(clean_subdir, exist_ok=True)  # 自动创建不存在的目录# 处理当前目录下的JSON文件for file in files:if file.lower().endswith('.json'):src_path = os.path.join(root, file)res_path = os.path.join(res_subdir, file)clean_path = os.path.join(clean_subdir, file)try:# 读取JSON数据with open(src_path, 'r', encoding='utf-8') as f:res = json.load(f)  # 解析JSON内容[3,9](@ref)# 使用自定义函数处理数据new_res = []clean_res = []for i in res:i.pop('content')i.pop('translate_time')translate_content = i.pop('translate_content')num_one = translate_content.count(' .')num_two = translate_content.count(' ...')num_thr = translate_content.count(' _')num_fou = translate_content.count(' |')all_num = (num_one - num_two) * 2 + num_two * 4 + num_thr * 2 + num_fou * 3if len(translate_content) <= 0:i['translate_content'] = translate_contentclean_res.append(i)continueprint(all_num)print(len(translate_content))print(all_num / len(translate_content))if all_num / len(translate_content) > 0.6 or len(translate_content.split()) < 500:i['translate_content'] = translate_contentclean_res.append(i)continuetranslate_content = translate_content.replace(' ...', '').replace(' .', '').replace(' _','').replace(' |','')i['translate_content'] = translate_contentnew_res.append(i)with open(res_path, 'w', encoding='utf-8') as f:json.dump(new_res, f, ensure_ascii=False, indent=4)if clean_res:with open(clean_path, 'w', encoding='utf-8') as f:json.dump(clean_res, f, ensure_ascii=False, indent=4)except Exception as e:print(f"处理文件失败 {src_path}: {str(e)}")if __name__ == '__main__':# 数据源data_path = 'data'# 处理后数据res_path = 'res'# 清理掉的数据clean_path = 'clean'run(data_path, res_path, clean_path)

http://www.dtcms.com/a/329166.html

相关文章:

  • 《工程封装》(Python)
  • 一键式商品信息获取:京东API返回值深度挖掘
  • Dynamsoft Capture Vision Crack
  • AWS Bedrock Claude模型费用深度分析:企业AI成本优化指南
  • 卫星轨道基础知识
  • ICCV 2025 | 4相机干掉480机位?CMU MonoFusion高斯泼溅重构4D人体!
  • LaTeX(排版系统)Texlive(环境)Vscode(编辑器)环境配置与安装
  • Pytest项目_day14(参数化、数据驱动)
  • duiLib 利用布局文件显示一个窗口并响应事件
  • C语言零基础第15讲:字符函数和字符串函数
  • ThinkPHP+Mysql 灵活用工小程序-技术深度解析与实践指南
  • 对线面试官之幂等和去重
  • 数据结构:用数组实现队列(Implementing Queue Using Array)
  • vue修改element的css属性
  • Docker端口映射完全指南:打通容器内外通信的关键技术
  • 如何把ubuntu 22.04下安装的mysql 8 的 数据目录迁移到另一个磁盘目录
  • 从“存得对”到“存得准”:MySQL 数据类型与约束全景指南
  • MySQL中的缓存机制
  • 浅谈TLS 混合密钥交换:后量子迁移过渡方案
  • openMVG---安装openMVG
  • C++主流string的使用
  • Linux内核的递归熵与异步系统守护进程的耦合解
  • 【类与对象(下)】探秘C++构造函数初始化列表
  • ROS机器人云实践案例设计
  • Git核心机制:工作区、暂存区与版本库
  • PG靶机 - Pelican
  • 【龙泽科技】汽车故障诊断仿真教学软件【科鲁兹】
  • (vue)el-table动态合并最后一行且内容靠左
  • CSS 多列布局(Multi-column Layout):快速上手指南
  • 基于UniApp的智能在线客服系统前端设计与实现