You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用DataFrame重命名图片名并解决Unicode编码问题?

解决方案

完整可运行代码

import pandas as pd
import os
import shutil

# 配置路径参数
input_folder = "input_folder"
out_folder = "out_folder"
imgs_input_dir = os.path.join(input_folder, "imgs")
imgs_output_dir = os.path.join(out_folder, "imgs")
jsonl_input_path = os.path.join(input_folder, "train.jsonl")
jsonl_output_path = os.path.join(out_folder, "train.jsonl")

# 自动创建输出目录(不存在则新建)
os.makedirs(imgs_output_dir, exist_ok=True)

# 读取JSONL数据到DataFrame
df = pd.read_json(jsonl_input_path, lines=True)

# 给file_name列添加前缀"A_"
# 注意:原代码里的df['file_name ']多了空格,会导致列名匹配失败,这里修正为df['file_name']
df['file_name'] = df['file_name'].apply(lambda x: f"A_{x}")

# 复制并重命名图片到输出目录
for _, row in df.iterrows():
    original_img_path = os.path.join(imgs_input_dir, row['file_name'].replace("A_", ""))
    new_img_path = os.path.join(imgs_output_dir, row['file_name'])
    shutil.copy(original_img_path, new_img_path)

# 保存处理后的JSONL,解决Unicode转义问题
# force_ascii=False 让特殊字符以原始UTF-8形式输出,而非转义序列
df.to_json(jsonl_output_path, orient="records", lines=True, force_ascii=False, encoding="utf-8")

关键细节说明

  • 列名修正:原代码中df['file_name ']多了一个空格,会触发KeyError,必须改成df['file_name']匹配正确列名。
  • Unicode转义解决:to_json时加上force_ascii=False,就能让匈牙利语等含特殊字符的文本直接显示原始字符(比如Elégedetlenek),不会变成El\u00e9gedetlenek;同时指定encoding="utf-8"保证文件编码正确。
  • 图片处理:用shutil.copy复制图片而非直接重命名,既保留原输入目录的文件,又在输出目录生成重命名后的新文件。
  • 目录兼容:os.makedirs(..., exist_ok=True)确保输出目录不存在时自动创建,避免运行报错。

最终效果

处理完成后:

  • 输出目录out_folder/imgs下的图片统一命名为A_0.jpg、A_1.jpg...
  • out_folder/train.jsonl中的file_name列同步更新,且所有文本的特殊字符都显示原始形态,无转义序列。

内容的提问来源于stack exchange,提问作者Mohammed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 08:42:20