文本存为json的代码

2019-08-07  本文已影响0人  布口袋_天晴了

文本存为上图所示的json格式,其代码如下:

list = []
    file = data_dir+'/'+data_dir+'.txt'
    fileObject = open(data_dir+'.json', 'w')
    with open(file, 'r', encoding='utf8') as f:
        line = f.readline().strip()
        while line:
            temp = line.split('\t')
            # print(temp)
            h_id = temp[0]
            t_id = temp[1]
            h = temp[2]
            t = temp[3]
            r = temp[4]
            sent = temp[5]
            d = {'sentence': sent,
                 'head': {'word': h, 'id': h_id},
                 'tail': {'word': t, 'id': t_id},
                 'relation': r}
            list.append(d)
            line = f.readline().strip()

    jsonData = json.dumps(list)
    fileObject.write(jsonData)
    fileObject.close()

文本json加载

data = json.load(open(file_name, "r"))
上一篇 下一篇

猜你喜欢

热点阅读