将文件导入python然后使用它

时间:2017-01-12 15:22:21

标签: 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 open('import.txt') as inputfile:
        for line in inputfile:
            data.append(line.strip().split(','))

到目前为止,我所拥有的对于我的生活无法理解如何在数据[]中获取这些数据并将其放入图表中以便可以用于算法。任何方向都将不胜感激!

在代码中,它被列为这个;

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

2 个答案:

答案 0 :(得分:2)

你可以这样做:

文件: graph_info.txt

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

代码: your_code.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]))

答案 1 :(得分:1)

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

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

# 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)
相关问题