文本存为上图所示的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"))
网友评论