Download script/format_trans/shuffle.py from bingqin111/data_process_bq: direct link, hf CLI and curl.
- Browser
- Download file 2.18 kB
-
https://huggingface.co/datasets/bingqin111/data_process_bq/resolve/main/script/format_trans/shuffle.py
- Command line
-
hf download hf://datasets/bingqin111/data_process_bq/script/format_trans/shuffle.py
-
curl -L -o shuffle.py https://huggingface.co/datasets/bingqin111/data_process_bq/resolve/main/script/format_trans/shuffle.py
2.18 kB
| import json | |
| import random | |
| import os | |
| # ----------------- 配置 ----------------- | |
| # 您的输入文件路径 (原文件) | |
| INPUT_FILE_PATH = "/root/test/weitiao/LLaMA-Factory/data/instag2100_BCD_sharegpt.json" | |
| # 您的输出文件路径 (打乱后保存的新文件) | |
| OUTPUT_FILE_PATH = "/root/test/weitiao/LLaMA-Factory/data/instag2100_BCD_sharegpt_shuffled.json" | |
| # ---------------------------------------- | |
| def shuffle_json_file_to_new_path(input_file_path, output_file_path): | |
| """ | |
| 读取 JSON 文件(假设内容是一个列表),打乱列表顺序,然后写入到新的文件路径。 | |
| """ | |
| print(f"开始处理输入文件: {input_file_path}") | |
| # 1. 检查输入文件是否存在 | |
| if not os.path.exists(input_file_path): | |
| print(f"错误: 输入文件不存在! 路径: {input_file_path}") | |
| return | |
| try: | |
| # 2. 读取数据 | |
| with open(input_file_path, 'r', encoding='utf-8') as f: | |
| # 假设文件内容是标准的 JSON 数组格式(列表) | |
| data = json.load(f) | |
| print(f"成功读取 {len(data)} 条语料。") | |
| # 3. 检查数据类型,确保可以打乱 | |
| if isinstance(data, list): | |
| # 4. 随机打乱列表顺序 | |
| random.shuffle(data) | |
| print("语料顺序已成功打乱。") | |
| else: | |
| print(f"警告: 文件内容不是一个列表 (list),而是 {type(data)}。无法进行打乱操作。") | |
| return | |
| # 5. 将打乱后的数据写入到新的文件 | |
| # 'w' 模式会创建文件或覆盖原有内容 | |
| with open(output_file_path, 'w', encoding='utf-8') as f: | |
| # indent=4 使输出的 JSON 带有格式化缩进,方便阅读 | |
| json.dump(data, f, ensure_ascii=False, indent=4) | |
| print(f"处理完成。打乱后的语料已成功写入新文件: {output_file_path}") | |
| except json.JSONDecodeError: | |
| print("错误: JSON 文件格式不正确,无法解析。请检查文件内容。") | |
| except Exception as e: | |
| print(f"处理过程中发生未知错误: {e}") | |
| # 执行函数 | |
| shuffle_json_file_to_new_path(INPUT_FILE_PATH, OUTPUT_FILE_PATH) |