我很难想象如何将一个文本文件解析成python的图形。这个文件的格式如下:
4 4
o . o . o . o
- - . -
o . o . o | o
. - . .
o | o . o . o
. - . -
o . o . o . o
顶部的整数表示行列尺寸。我需要考虑每个字符之间的空格。这应该代表一个迷宫,我将在其中运行搜索以确定给定起点和终点的最佳路径。那部分我已经想出来了。我只需要帮助将此文本文件解析为图形,以便我可以运行搜索。
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'))
具体实现取决于您想如何在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))
这应该能工作,但我还没有测试过,现在就去测试一下。
"""
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)
name 'graph' is not defined
)。这是你创建的一种自定义类型吗?还是你没有具体的想法,希望我们提供一个合适的表示方法? - Mark Byers