5

I'm having trouble figuring out how to parse a text file into a graph 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 take into account the space between each character. This is suppose to represent a maze that I'll have to run a search on to determine the optimal path given a start and endpoint. That part I have figured out. I simply need help parsing this text file into a graph so I can run the search.

1
  • What specifically do you mean by parsing to a "graph"? Is there a "graph" built-in type in Python? (I get name 'graph' is not defined). Is it some custom type you have created? Or don't you have any specific ideas and you want us to suggest a suitable representation? Commented Dec 10, 2011 at 20:02

3 Answers 3

2

This function parses a grid like the one you've given into a set of nodes (stored as a pair of coordinates in the original grid), and a dict of edges (mapping each node to a list of nodes that are adjacent to it). This is a very easy-to-use representation for the graph, and you should have no trouble coding the maze search using it. The code uses the idea that the structure of the maze is described by just the edges (- and |), and that the grid is double-line spaced horizontally and vertically. A square with no edges into or out of it will not appear in the graph.

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'))
Sign up to request clarification or add additional context in comments.

1 Comment

I basically coded the same and posted... then the page refreshed and I saw you did it before me... No other chance than delete mine and upvote yours! ;)
0

The implementation would depend on how you want to represent the graph in Python.

I'm creating an edge list

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))

this should work, but i havn't tested it yet, going to do that now.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.