使用python中的文本文件输入创建图形

时间:2017-11-11 19:37:59

标签: python list graph depth-first-search

我有以下txt文件:

31  1262    -1
531 13930   1
531 16139   -1
531 17567   1
531 20653   1

第一列显示起始节点,第二列显示结束节点。我想创建一个像

这样的图表
graph = {'0': set(['1', '2']),
         '1': set(['0', '3', '4']),
         '2': set(['0']),
         '3': set(['1']),
         '4': set(['2', '3'])}

使用文本文件中的输入。我保存了start_vertex = []中的第一列和end_vertex = []中的第二列。我在下面编写了代码,但我无法保存图表。

for i in range(len(lines)):
    v = start_vertex[i]
    if v == start_vertex[i]:
        graph = graph + {'v' : set(['end_vertex[i]'])}

完整的代码在这里:

file = open("network.txt","r")
lines = file.readlines()
start_vertex = []
end_vertex = []
sign = []
graph = []

for x in lines:
    start_vertex.append(x.split('\t')[0])
    end_vertex.append(x.split('\t')[1])
    sign.append(x.split('\t')[2])
file.close()


def dfs(graph, start, visited = None):
    if visited is None:
        visited = set()
        visited.add(start)
        print(start)
        for next in graph[start] - visited:
            dfs(graph, next, visited)
        return visited

for i in range(len(lines)):
    v = start_vertex[i]
    if v == start_vertex[i]:
        graph = graph + {'v' : set(['end_vertex[i]'])}

1 个答案:

答案 0 :(得分:1)

从您的问题来看,目前尚不清楚您的确切输入是什么以及预期输出是多少。您没有提到输入文本文件中第三列的含义。此外,您的程序存在严重问题。

我猜您正在尝试按如下方式存储输入图。

2017-11-13 is equal to Monday, 13 of November from year 2017
2017-11-14 is equal to Tuesday, 14 of November from year 2017
2017-11-15 is equal to Wednesday, 15 of November from year 2017

<强>输出

lines = [(31, 1262, -1), (531, 13930, 1), (531, 16139, -1), (531, 17567, 1), (531, 20653, 1)]
start_vertex, end_vertex = [], []
for line in lines:
    start_vertex.append(line[0])
    end_vertex.append(line[1])

graph = {}
for i in range(len(lines)):
    v = start_vertex[i]
    if v in graph:
        graph[v] |= set([end_vertex[i]])
    else:
        graph[v] = set([end_vertex[i]])

print(graph)

格式为:{531: {13930, 16139, 20653, 17567}, 31: {1262}}