前言

pandas 是一个非常有用的 Python 第三方库。

操作系统:Windows 10 专业版

参考文档

  1. execel转换成json

将 excel 数据转化为 json

项目源码地址:https://github.com/LuYF-Lemon-love/ChatPhaLaw/blob/main/excel2json.ipynb

excel 文件一共两列,第二列是以 问:答: 开头的多个问答数据(也可能没有),第一列是问答数据的上下文。

导入第三方库

1
2
3
import os
import numpy as np
import pandas as pd

将 excel 数据转化为 json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 读取 excel 文件
def read_excel(file_name):
json_list = []
excel_data = pd.read_excel(file_name)
for index, Series in excel_data.iterrows():
if Series[1] is np.nan:
continue
ls = Series[1].replace('问:', '@').replace('答:', '@').strip('@').split('@')
if len(ls) % 2 == 1:
continue
question_respone = []
for i, sentence in enumerate(ls):
question_respone.append(sentence.strip())
if i % 2 == 1:
json_list.append(question_respone)
question_respone = []
return json_list
1
2
3
4
5
6
7
8
9
10
# 读取当前目录下的所有 excel 文件
folder_path = 'pharmaceutical_law'
json_list = []
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.xlsx'):
file_path = os.path.join(root, file)
print(file_path)
json_list += read_excel(file_path)
print(f'一共{len(json_list)}条数据。')

1
print(json_list[0])
1
['什么是药品标准?', '药品标准是衡量药品安全、有效和质量可控的标尺。']

1
2
json_data = pd.DataFrame(json_list, columns=['instruction', 'output'])
print(json_data)

1
json_data.to_json(path_or_buf='data_without_context.json', orient='records', force_ascii=False, indent=4)

结语

第九十二篇博文写完,开心!!!!

今天,也是充满希望的一天。