美文网首页
文本存为json的代码

文本存为json的代码

作者: 布口袋_天晴了 | 来源:发表于2019-08-07 18:43 被阅读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"))

相关文章

网友评论

      本文标题:文本存为json的代码

      本文链接:https://www.haomeiwen.com/subject/tumadctx.html