我有一个格式的数据:
id1 id2 值 类似
1 234 0.2
1 235 0.1
等等。我想将其转换为 json 格式:
{
"nodes": [ {"name":"1"}, #first element
{"name":"234"}, #second element
{"name":"235"} #third element
] ,
"links":[{"source":1,"target":2,"value":0.2},
{"source":1,"target":3,"value":0.1}
]
}
因此,从原始数据到上述格式.. 节点包含原始数据中存在的所有(不同)名称集,链接基本上是节点返回的值列表中源和目标的行号。例如:
1 234 0.2
1 在键“nodes”持有的值列表中的第一个元素中 234 是键“nodes”持有的值列表中的第二个元素
因此链接字典是 {"source":1,"target":2,"value":0.2}
我如何在python中有效地做到这一点..我相信应该有比我正在做的更好的方法,这太混乱了:(这是我从集合导入defaultdict所做的
def open_file(filename,output=None):
f = open(filename,"r")
offset = 3429
data_dict = {}
node_list = []
node_dict = {}
link_list = []
num_lines = 0
line_ids = []
for line in f:
line = line.strip()
tokens = line.split()
mod_wid = int(tokens[1]) + offset
if not node_dict.has_key(tokens[0]):
d = {"name": tokens[0],"group":1}
node_list.append(d)
node_dict[tokens[0]] = True
line_ids.append(tokens[0])
if not node_dict.has_key(mod_wid):
d = {"name": str(mod_wid),"group":1}
node_list.append(d)
node_dict[mod_wid] = True
line_ids.append(mod_wid)
link_d = {"source": line_ids.index(tokens[0]),"target":line_ids.index(mod_wid),"value":tokens[2]}
link_list.append(link_d)
if num_lines > 10000:
break
num_lines +=1
data_dict = {"nodes":node_list, "links":link_list}
print "{\n"
for k,v in data_dict.items():
print '"'+k +'"' +":\n [ \n "
for each_v in v:
print each_v ,","
print "\n],"
print "}"
open_file("lda_input.tsv")