Parsing from text file to graph (python)

I am having trouble figuring out how to parse a text file in graphics in python. The file is in the following format:

4 4 
o . o . o . o
-   -   .   -
o . o . o | o 
.   -   .   .
o | o . o . o
.   -   .   -
o . o . o . o 

The integers at the top are the dimensions (row, column). I need to consider the space between each character. Suppose this is a maze that I have to do to search in order to determine the optimal path, taking into account the beginning and end point. I understood this part. I just need help analyzing this text file in the graph so that I can run the search.

+5
source share
3 answers

, , , ( ) ( node , ). , , . , (- |) , . .

import collections

def parse_grid(grid):
    edges = collections.defaultdict(list)
    for i in xrange(len(grid)):
        for j in xrange(len(grid[i])):
            if grid[i][j] == '-':
                edges[i, j - 2].append((i, j + 2))
                edges[i, j + 2].append((i, j - 2))
            if grid[i][j] == '|':
                edges[i - 2, j].append((i + 2,j))
                edges[i + 2, j].append((i - 2,j))
    nodes = set()
    for e in edges.iterkeys():
        nodes.add(e)
    return nodes, edges

grid = """\
o . o . o . o
-   -   .   -
o . o . o | o 
.   -   .   .
o | o . o . o
.   -   .   -
o . o . o . o"""
print parse_grid(grid.split('\n'))
+2

, Python.

edgelist = []
y=0
for line in file:

    chars = [char for char in line.split(" ") if len(char)]
    x = 0

    if ('|' in chars):
        y+=1
        for char in chars:
            if char == 'o'
                x+=1
            elif char == '.'
                edgelist.append([(x,y),(x+1,y)])
    else:
        for char in chars:
            x+=1
            if char == '.'
                edges.append([(y,x),(y,x+1))

, , .

0
"""
maze1.txt

4 4
o . o . o . o
-   -   .   -
o . o . o | o
.   -   .   .
o | o . o . o
.   -   .   -
o . o . o . o
"""

readfile = open('maze1.txt', 'r')
line = readfile.readline()
rowcount, colcount = [int(elem) for elem in line.strip().split(' ')]
rights = []
downs = []
chars =      ('o', '   ', '.', '-', '|', '')
translated = ('o', '   ', '.', '-', '|', '') # if needed, could be int or method

while line:
    line = readfile.readline()
    if chars[0] in line:
        for elem in line.strip().split(chars[0])[1:]:
            rights.append(translated[chars.index(elem.strip())])
    else:
        for elem in line.strip().split(chars[1])[:colcount]:
            downs.append(translated[chars.index(elem.strip())])


readfile.close()

for i, elem in enumerate(rights):
    print elem, divmod(i, colcount)
print "##"
for i, elem in enumerate(downs):
    print elem, divmod(i, colcount)
0
source

All Articles