python 从输入文件解析邻接矩阵

python parse adjacency matrix from an input file

我有一个输入 .txt 文件,其邻接矩阵如下所示:

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

如何将此输入解析为二维数组或嵌套字典?

例如

map['A']['B'] = 55
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
from io import StringIO
d = StringIO(u"    A    B    C\nA   0    55   0\nB   55   0    0\nC   0    0    0\n")

import pandas as pd
map = pd.read_table(d, header=0, index_col=0, delim_whitespace=True)

print(map)
    A   B  C
A   0  55  0
B  55   0  0
C   0   0  0
print(map['A']['B'])
55