sinopec-safe-questions-analyse/选择.py
2025-08-12 20:47:01 +08:00

69 lines
2.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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)