读取 json 文件
读取json文件
with open(file_path) as f:
json_data = json.load(f)
若 json
文件的格式如下:
[
{
"img_path": "path/to/image1.jpg",
"question": "这张图片中有什么?",
"candidates": [
"猫",
"狗",
"鸟",
"鱼"
],
"correct_ans": "猫"
},
{
"img_path": "path/to/image2.jpg",
"question": "这张图片中的主要颜色是什么?",
"candidates": [
"红色",
"蓝色",
"绿色",
"黄色"
],
"correct_ans": "蓝色"
}
]
获取 json
文件的内容:
for i, data in enumerate((json_data)):
# 获取图像文件路径
filename = data ["img_path"]
# 初始化消息字符串,包含问题文本和换行符
message = data ["question"] + "\n"
# 遍历选项和候选答案
for choice, ans in zip(["A.", "B.", "C.", "D."], data ["candidates"]):
# 将选项和答案添加到消息字符串中
message += f"{choice} {ans}\n"
# 如果存在正确答案且当前答案是正确答案,记录正确选项的字母
if "correct_ans" in data and ans == data ["correct_ans"]:
correct_choice = choice[0]
# 非必须,根据语言设置添加相应的提示信息
# if args.language == "en":
# # 英文提示
# message = message + "Answer with the option's letter from the given choices directly.\n"
# elif args.language == "ch":
# # 中文提示
# message = message + "请直接回答正确选项的字母\n"
# else:
# # 中文提示
# aise NotImplementedError("Does not support languages other than English (en) and Chinese (ch) yet. ")