Home > Back-end >  Extracting a graph from a text file to a python graph
Extracting a graph from a text file to a python graph

Time:12-14

I have a text file with the following graph inside:

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:

I've been trying to extract this graph into a python graph that is formatted like the example below:

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': {}
    }

I am new to python and cannot figure it out. I've tried using the code below, but it just loads the graph into an array. I am unsure of how to form it into the graph example above.

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

output of above code:

['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:']

CodePudding user response:

Try storing a variable and slicing every other value in the lines to create the key - value pairs to construct the dictionary, if there is nothing after the colon, it feeds and empty dictionary:

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 {})})

CodePudding user response:

You can do this by splitting each line by spaces, then you can take the first element of the split and get rid of the ':' to get the start of the edge and process the rest of the entries two at a time, the first being the other node in the edge and the entry being the number. Then you can just put each intermediate result into a dictionary:

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
  • Related