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

时间:2017-07-13 18:57:07

标签: python parsing adjacency-matrix

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

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

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

e.g。

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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