[英]python parse adjacency matrix from an input file
我正在输入带有邻接矩阵的.txt文件,如下所示:
A B C
A 0 55 0
B 55 0 0
C 0 0 0
如何将该输入解析为2D数组或嵌套字典?
例如
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.