将文件导入python并使用它

将文件导入python并使用它,python,python-2.7,Python,Python 2.7,用这个来计算最短路径 我想做的不是让程序中的节点和距离,而是把它们放在一个文本文件中,让它加载它们,而不是程序中的节点和距离 # Use Graph() g = Graph() #Define a new array data = [] # Open the import.txt file and import it into the array removing black space and splitting at commas. with ope

用这个来计算最短路径

我想做的不是让程序中的节点和距离,而是把它们放在一个文本文件中,让它加载它们,而不是程序中的节点和距离

 # Use Graph()
    g = Graph()
    #Define a new array
    data = []
    # Open the import.txt file and import it into the array removing black space and splitting at commas.
    with open('import.txt') as inputfile:
        for line in inputfile:
            data.append(line.strip().split(','))
是我迄今为止所拥有的,但我无法确定如何在data[]中获取这些数据,并将其放入图形中,以便用于算法。任何方向都将不胜感激

在代码中,它被列为:

g = Graph()

g.add_vertex('a')
g.add_vertex('b')
g.add_vertex('c')
g.add_vertex('d')
g.add_vertex('e')
g.add_vertex('f')

g.add_edge('a', 'b', 7)  
g.add_edge('a', 'c', 9)
g.add_edge('a', 'f', 14)
g.add_edge('b', 'c', 10)
g.add_edge('b', 'd', 15)
g.add_edge('c', 'd', 11)
g.add_edge('c', 'f', 2)
g.add_edge('d', 'e', 6)
g.add_edge('e', 'f', 9)
然而,我想把它放在一个文本文件中,这样就可以很容易地更改。想要使用的文本文件id的一个示例是

'a', 'e', 2
'a', 'b', 5
'b', 'c', 9
'e', 'c', 8
'e', 'd', 7
'd', 'c', 1

你可以这样做:

文件:graph\u info.txt

a, e, 2
a, b, 5
b, c, 9
e, c, 8
e, d, 7
d, c, 1
代码:您的代码.py

content = ''
with open('graph_info.txt', 'r') as f:
    content = f.read()


vertex_dict = {}
edges_list = []

lines = content.split('\n')

for l in lines:
    edge_info = l.split(', ')
    edges_list.append(edge_info)
    if edge_info[0] not in vertex_dict:
        vertex_dict[edge_info[0]] = True
    if edge_info[1] not in vertex_dict:
        vertex_dict[edge_info[1]] = True

# populating graph information
g = Graph()

for vertex_name, dummy in vertex_dict.iteritems():
    g.add_vertex(vertex_name)

for edge_info in edges_list:
    g.add_edge(edge_info[0], edge_info[1], int(edge_info[2]))

这实际上只是对爱默生·卡多佐的优秀答案的提炼。由于要创建逗号分隔值文件,因此应使用
csv
模块对其进行解析。此外,我认为在解析它们之前不需要创建一个顶点/边列表——您只需要一组顶点名称,就可以创建任何尚未看到的顶点

# filename.csv
a, e, 2
a, b, 5
b, c, 9
e, c, 8
e, d, 7
d, c, 1


@ScottHunter抱歉,我更新了链接,但我不知道它已断开。希望这能比我解释得更好。然而,它被用来存储节点和顶点以进行计算。就Python而言,
data
只是一个字符串列表。我不知道这样的字符串包含什么,但底线是,
数据
应该将其转换为与您相关的数据。您可能可以通过使用或旧的(和unsafer)来实现这一点。
# yourscript.py
import csv

g = Graph()
vertices = set()

with open("filename.csv") as csv_f:
    reader = csv.reader(csv_f)
    for line in reader:
        from_, to, distance = line
        if from_ not in vertices:
            g.add_vertex(from_)
            vertices.add(from_)
        if to not in vertices:
            g.add_vertex(to)
            vertices.add(to)
        g.add_edge(from_, to, distance)