如何将列表存储至json文件再读取至其他代码中
在多模态任务中,常常需要使用预训练的模型去提取不同模态的特征信息,本代码可以搭建在代码内,直接使用源码来训练模型并获取表示,再将特征信息导入到多模态代码内进行后续的特征融合、推理等操作。
# 定义自己的list,将要存储的内容都存入list
list = []
list.append({'name': joey,
'phon_enumber':66666})
# 将list存入json文件中
os.makedirs(json_file_dirpath, exist_ok=True) # 创建文件夹
json_file_path = os.path.join(json_file_dirpath, 'entity_id2emb.json') # 设置文件名
with open(json_file_path, 'w+') as json_file:
json.dump(list, json_file, indent=4, separators=(',', ': '))
# 将json文件读取回代码中
with open(json_file_path, 'r') as json_file:
loaded_list = json.load(json_file) # loaded_list即为存入的list
如果要存入list中的某部分元素为tensor张量,需要将其转化成为numpy数组再转化成列表list,再存入文件中,具体代码如下:
vector = vector.numpy().tolist()
vector = vector.cpu().detach().numpy().tolist()