我有一个以.txt文件编码的有向图(大约24k行)。每一行的格式均为"superNodeName : listOfnodeNamesToCollapseIntoThisSupernode"
我需要将一些节点折叠成超级节点。我有一个字典,其中每个元素都在表单中 {{1}}(dict有10个元素)。我认为最好的方法是修改"该图表适用于.txt文件。
如何用超级节点名称替换要折叠的节点名称文件中的每个匹配项?
答案 0 :(得分:0)
# Your super node dictionnary
super_node = {'name': [...]}
new_text = ''
# Open your txt file
with open('test.txt') as f:
for line in f.readlines():
# Split each line
splitted = line.split(':')
for n, n_list in super_node.items():
if splitted[0] in n_list: # Source is in super node
splitted[0] = n # Replace node name
if splitted[1] in n_list: # Destination is in super node
splitted[1] = n # Replace node name
# Add to new text
new_text += '{0}\n'.format(':'.join(splitted))
# Write text file
with open('text.txt', 'w') as f:
f.write(new_text)