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

复制代码
import pandas as pd
import json

# 1. 读取 Excel 文件(假设列名为 question 和 answer)
try:
    df = pd.read_excel("input.xlsx", usecols=["question", "answer"])  # 明确指定列
except Exception as e:
    print(f"读取文件失败: {str(e)}")
    exit()

# 2. 转换为字典列表
result = [
    {"question": str(row["question"]), "answer": str(row["answer"])}
    for _, row in df.iterrows()
]

# 3. 写入 JSON 文件
with open("train_qa.json", "w", encoding="utf-8") as f:
    json.dump(result, f, ensure_ascii=False, indent=2)

print("转换成功!")
相关推荐
曲幽3 小时前
FastAPI + PostgreSQL 实战:从入门到不踩坑,一次讲透
python·sql·postgresql·fastapi·web·postgres·db·asyncpg
用户8356290780518 小时前
使用 C# 在 Excel 中创建数据透视表
后端·python
码路飞11 小时前
FastMCP 实战:一个 .py 文件,给 Claude Code 装上 3 个超实用工具
python·ai编程·mcp
dev派13 小时前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
前端付豪14 小时前
AI 数学辅导老师项目构想和初始化
前端·后端·python
用户03321266636715 小时前
将 PDF 文档转换为图片【Python 教程】
python
悟空爬虫16 小时前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python
dev派16 小时前
AI Agent 系统中的常用 Workflow 模式(1)
python·langchain
明月_清风18 小时前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python
曲幽1 天前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic