首页 前端知识 【最全的excel转json!!!】使用Python脚本提取excel文本中的数据到json中

【最全的excel转json!!!】使用Python脚本提取excel文本中的数据到json中

2024-08-22 23:08:46 前端知识 前端哥 261 611 我要收藏

比如说:我有一个1.xlsx的文件需要转成对应的json格式。

1)
excel 文件的大概内容:
在这里插入图片描述
在这里插入图片描述
2)保存的方式类似于以下这种情况:
在这里插入图片描述
用Python脚本来实现

import pandas as pd
import json
# 读取Excel文件
excel_path = r"D:\1.xlsx"
df = pd.read_excel(excel_path)
# 输出DataFrame的列名
print(df.columns)
# 确认是否包含名为 'Response' 的列
if 'response' not in df.columns:
raise KeyError("No 'Response' column found in the Excel file.")
# 确认是否包含名为 'case' 的列
if 'CASE' not in df.columns:
raise KeyError("No 'CASE' column found in the Excel file.")
# 提取CASE列和Response列的数据
data = {}
for index, row in df.iterrows():
case = row['CASE'] # 提取 CASE 列的数据
response = row['response'] # 提取 Response 列的数据
data[index] = {
"origin_prompt": [
{
"prompt": case # 将 CASE 数据作为原始提示存储
}
],
"prediction": response # 存储 Response 数据
}
# 将数据保存为JSON文件,并按照中文形式保存
json_path = r"D:\1.json"
with open(json_path, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
print(f"JSON 文件已生成:{json_path}")
复制

代码中先读取的是D盘路径下的1.xlsx文件的内容,然后经过处理后保存到了D盘路径下的1.json文件中。

转载请注明出处或者链接地址:https://www.qianduange.cn//article/16578.html
标签
评论
发布的文章

安装Nodejs后,npm无法使用

2024-11-30 11:11:38

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!