从文本文件中提取图形并生成Python图表

3

我有一个文本文件,里面包含以下的图表:

1: 2 3 4 5 6 2
2: 3 -4
3: 8 4
4: 5 6
5: 4 -3 8 8
6: 7 3
7: 6 -6 8 7
8:

我一直在尝试将这张图提取为一个格式类似于下面示例的Python图表:

graph = {
        '1': {'2': 3, '4': 5, '6': 2},
        '2': {'3': -4},
        '3': {'8': 4},
        '4': {'5': 6},
        '5': {'4': -3, '8': 8},
        '6': {'7': 3},
        '7': {'6': -6, '8': 7},
        '8': {}
    }

我是Python新手,无法理解它。我尝试使用下面的代码,但它只是将图加载到数组中。我不确定如何将其组成上面的图形示例。

graph = []                                 
    with open(fileName,'r') as file:           
        for line in file:                      
            for line in line[:-1].split():  
                    graph.append(line)          

以上代码的输出结果:

['1:', '2', '3', '4', '5', '6', '2', '2:', '3', '-4', '3:', '8', '4', '4:', '5', '6', '5:', '4', '-3', '8', '8', '6:', '7', '3', '7:', '6', '-6', '8', '7', '8:']

它将它加载到数组中,因为你只是将每行分割然后附加到数组中。你需要使用一个字典。 - Kevin Welch
我不熟悉如何使用字典。这应该怎么实现? - Tyler
2个回答

2
尝试存储一个变量并切片每行的每个其他值以创建键-值对来构建字典,如果冒号后面没有任何内容,则提供一个空字典。
graph = []
with open(fileName,'r') as file:           
    for line in file:                      
        graph.append({line.split(':')[0].replace(' ', ''): (dict(zip(line.split(': ')[1].split()[::2], map(int, line.split(': ')[1].split()[1::2]))) if ': ' in line else {})})

1
你可以通过按空格分割每一行来实现这个功能,然后您可以获取拆分的第一个元素并去掉 ':' 来获取边的起点,并且以两个为一组处理其余条目,第一个是边的另一个节点,而条目则是数字。然后,您可以将每个中间结果放入字典中:
graph = {}
with open(fileName,'r') as file: 
    for line in file:
        s = line.split(' ')
        u = s[0].strip(':')
        graph[u] = {}
        for i in range(1, len(s), 2):
            v = s[i]
            c = int(s[i + 1])
            graph[u][v] = c

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接