python json文件写入数据

python json文件写入数据

##代码如下

import os
import numpy as np
from collections import defaultdict, OrderedDict
import json
from pathlib import Path

scripts = []
scp_dir  = './data.txt'  #txt文件记录了每条数据的存储路径
with open(scp_dir,encoding='utf-8') as f :
    for l in f.readlines():
        scripts.append(Path(l.strip('\n')))  #读取每一条数据的存储路径


spk_data = []  
label = []

for src_p in scripts:
    all_speaker =['p329', 'p361', 'p335', 'p341', 'p313']#5个speaker
    species_to_id = dict((c, i) for i, c in enumerate(all_speaker)) #给speaker赋label

    src_p_speaker_r = os.path.basename(src_p).split('spk_emb_')[-1]
    src_p_speaker = os.path.basename(src_p_speaker_r).split('_')[0]
    src_root = os.path.dirname(src_p)
    # print('-------------')
    src_mel_pad = np.load(str(src_p))##读取数据内容
    # src_mel_pad = torch.FloatTensor(src_mel_pad)

    src_p_speaker_label =species_to_id.get(src_p_speaker)
    spk_data.append(src_mel_pad.tolist())
    label.append(src_p_speaker_label)
    # print(spk_data)

result={'data':spk_data,'label':label}##以字典形式存入json
with open('test_data.json', 'w') as json_file:
    json_str = json.dumps(result)
    json_file.write(json_str)

你可能感兴趣的:(语音,python,json,深度学习)