替换fi线路的一部分

2024-10-17 06:27:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有向图编码在一个.txt文件(约24k行)。每一行的形式都是sourceNode:destinationNode:edgeWeight

我需要把一些节点折叠成超级节点。我有一本字典,里面的每一个元素都是 "superNodeName : listOfnodeNamesToCollapseIntoThisSupernode"(dict有10个元素)。我认为“修改”图表的最好方法是处理.txt文件

如何用超级节点名称替换要折叠的节点名称在文件中的每个引用


Tags: 文件txt名称元素编码字典节点图表
1条回答
网友
1楼 · 发布于 2024-10-17 06:27:42
# 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)

相关问题 更多 >