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

pandas实现Excel转JSON时如何为EN列每行值设置自定义键

实现步骤

你可以按照以下流程完成需求,全程基于pandas实现,不需要额外引入复杂依赖:

  • 首先安装读取Excel需要的依赖:
    pip install pandas openpyxl
  • 核心实现逻辑:
    1. 读取Excel文件拿到表格数据
    2. 遍历EN列的所有取值(默认自动去重,避免重复输入相同词条的键)
    3. 逐行弹出交互提示,收集用户输入的自定义键,形成「自定义键-原词条」的映射关系
    4. 基于映射关系重组数据结构,导出为JSON文件
完整可运行代码
import pandas as pd
import json

# 1. 读取Excel文件,替换成你的实际文件路径
df = pd.read_excel("your_translate_file.xlsx")

# 2. 交互式收集自定义键
key_mapping = {}
# 遍历EN列去重后的值,相同EN词条无需重复输入
for en_term in df["EN"].unique():
    custom_key = input(f'Please insert key for "{en_term}" \n - ')
    key_mapping[custom_key] = en_term

# 3. 重组为目标JSON结构
output_data = {}
for custom_key, en_term in key_mapping.items():
    # 匹配对应词条的多语言内容
    term_info = df[df["EN"] == en_term].to_dict("records")[0]
    output_data[custom_key] = {
        "EN": term_info["EN"],
        "DE": term_info["DE"],
        "RU": term_info["RU"]
    }

# 4. 导出格式化后的JSON文件
with open("translate_result.json", "w", encoding="utf-8") as f:
    json.dump(output_data, f, ensure_ascii=False, indent=2)
运行效果说明

代码启动后会按EN列的顺序逐行弹出输入提示,和你预期的交互形式完全一致:

Please insert key for "Ball" 
 - myBallKey
Please insert key for "Snow" 
 - myKeyForSnow

所有词条输入完成后,会在脚本同目录生成translate_result.json文件,输出结构示例如下:

{
  "myBallKey": {
    "EN": "Ball",
    "DE": "Ball",
    "RU": "AA"
  },
  "myKeyForSnow": {
    "EN": "Snow",
    "DE": "Schnee",
    "RU": "BB"
  }
}

如果你的Excel里存在重复EN词条(比如同一个英文对应不同翻译的特殊场景),只需要把遍历逻辑里的df["EN"].unique()替换为df["EN"],就会逐行触发输入提示,不会自动合并重复项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 08:18:27