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

excel文件有两列,循环读取文件两列赋值到字典列表。字典的有两个key,分别为question和answer。将最终结果追加到json文件

import pandas as pd
import json
import os

def excel_to_json_append(excel_path, json_path):
    # 1. 读取Excel数据到字典列表
    df = pd.read_excel(excel_path, usecols=["question", "answer"])
    new_data = [
        {"question": str(row["question"]), "answer": str(row["answer"])}
        for _, row in df.iterrows()
    ]

    # 2. 读取原有JSON数据(如果文件存在)
    existing_data = []
    if os.path.exists(json_path):
        try:
            with open(json_path, "r", encoding="utf-8") as f:
                existing_data = json.load(f)
        except json.JSONDecodeError:
            print("警告:JSON文件内容格式异常,将覆盖写入")

    # 3. 合并新旧数据(可选去重逻辑)
    combined_data = existing_data + new_data
    # # 4.去重
    # seen = set()
    # unique_data = []
    # for item in combined_data:
    #     key = item["question"]
    #     if key not in seen:
    #         seen.add(key)
    #         unique_data.append(item)
    # combined_data = unique_data

    # 4. 写入更新后的JSON文件
    with open(json_path, "w", encoding="utf-8") as f:
        json.dump(combined_data, f, ensure_ascii=False, indent=2)

    print(f"成功追加{len(new_data)}条数据到{json_path}")

# 示例用法
excel_to_json_append("input.xlsx", "train_qa.json")

相关文章:

  • C语言:字符串去特定字符
  • UGO和ACL
  • 从关键词到权重:TF-IDF算法解析
  • Atom of Thoughts for Markov LLM Test-Time Scaling论文解读
  • 凸集和凸函数
  • Google C++编码规范指南(含pdf)
  • python主成分分析法1
  • MyBatis 配置文件解析使用了哪些设计模式
  • 在 Dojo 框架中define、declare 和 require的区别
  • 【自用】NLP算法面经(5)
  • 美摄接入DeepSeek等大模型,用多模态融合重构视频创作新边界!
  • 从零开发数据可视化
  • node-ddk,electron 组件, 系统基上下文菜单(右键菜单)
  • qt 图像后处理的软件一
  • spring boot3 验证码工具kaptcha使用
  • vue 自制列表,循环滚动
  • python本地连接minio
  • Python:单继承方法的重写
  • (十六) 60s搞懂 : Zookeeper 的详细安装,使用及注意事项
  • Linux多核调度:解锁CPU潜能的密码
  • 2025年“新时代网络文明公益广告”征集展示活动在沪启动
  • 人形机器人灵犀X2掌握新技能:有了“内心戏”,还会拳脚功夫
  • 收到延期付款利息,该缴纳增值税吗?
  • 普京调整俄陆军高层人事任命
  • 深圳拟出让3宗居住用地,共计用地面积6.77公顷
  • 走进“双遗之城”,领略文武风采:沧州何以成文旅新贵