Search code examples
pythonparsingadjacency-matrix

python parse adjacency matrix from an input file


I'm having a input .txt file with adjacency matrix looks like:

    A    B    C
A   0    55   0
B   55   0    0
C   0    0    0

How can I parse this input into a 2D array or nested dictionary?

e.g.

map['A']['B'] = 55

Solution

  • import StringIO
    
    # this is just for the sake of a self-contained example
    # this would be your actual file opened with open()
    inf = StringIO.StringIO("    A    B    C\n"
            "A   0    55   0\n"
            "B   55   0    0\n"
            "C   0    0    0")
    
    import re
    map = {}
    lines = inf.readlines()
    headers = []
    
    # extract each group of consecutive word characters. 
    # If your headers might contain dashes or other non-word characters,
    # you might want ([^\s]+) instead.
    for header in re.findall('(\w+)', lines[0]):
        headers.append(header)
        map[header] = {}
    
    for line in lines[1:]:
        items = re.findall('(\w+)', line)
        rowname = items[0]
        for idx, item in enumerate(items[1:]):
            map[headers[idx]][rowname] = item
    
    print map