69 lines
2.4 KiB
Python
69 lines
2.4 KiB
Python
import csv
|
||
import json
|
||
|
||
def convert_csv_to_json(input_csv_path, output_json_path):
|
||
"""
|
||
将指定的CSV文件转换为每行一个JSON对象的格式。
|
||
|
||
Args:
|
||
input_csv_path (str): 输入CSV文件的路径。
|
||
output_json_path (str): 输出JSON文件的路径。
|
||
"""
|
||
try:
|
||
with open(input_csv_path, 'r', encoding='utf-8') as csv_file, \
|
||
open(output_json_path, 'w', encoding='utf-8') as json_file:
|
||
|
||
# 使用csv.reader读取文件,csv.DictReader也可以,但索引更直接
|
||
csv_reader = csv.reader(csv_file)
|
||
|
||
# 跳过表头
|
||
header = next(csv_reader)
|
||
|
||
# 选项字母列表
|
||
option_letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
|
||
|
||
# 遍历每一行数据
|
||
for row in csv_reader:
|
||
# 检查行是否为空或无效
|
||
if not row or len(row) < 10:
|
||
continue
|
||
|
||
# 提取问题(第1列,索引0)
|
||
question = row[0]
|
||
|
||
# 提取正确答案(第10列,索引9)
|
||
correct_answer = row[9]
|
||
|
||
# 提取选项(从第2列到第9列,索引1到8)
|
||
options = []
|
||
for i in range(len(option_letters)):
|
||
option_text = row[i+1].strip()
|
||
if option_text:
|
||
# 格式化选项为 "A. 文本"
|
||
options.append(f"{option_letters[i]}.{option_text}")
|
||
|
||
# 创建JSON对象
|
||
json_object = {
|
||
"q": question,
|
||
"a": options,
|
||
"ans": correct_answer
|
||
}
|
||
|
||
# 将JSON对象写入文件,每行一个对象
|
||
json_file.write(json.dumps(json_object, ensure_ascii=False) + '\n')
|
||
|
||
print(f"转换成功!文件已保存到:{output_json_path}")
|
||
|
||
except FileNotFoundError:
|
||
print(f"错误:找不到文件 {input_csv_path}")
|
||
except Exception as e:
|
||
print(f"发生错误:{e}")
|
||
|
||
# 请将'单选题.csv'替换为您的实际文件路径
|
||
input_file = '多选题.csv'
|
||
output_file = 'output.json'
|
||
|
||
if __name__ == "__main__":
|
||
convert_csv_to_json(input_file, output_file)
|
||
|