将文件转换为矩阵,在 Python 中将每个字符替换为数字



按照说明解决迷宫问题,我需要从文件中读取,然后将其转换为矩阵。完成此操作后,我需要将每个"#"(代表一堵墙)替换为 -1,将每个"(代表走廊)替换为 0,将每个"M"(代表牛头怪)替换为 -2。我已经设法将文件转换为矩阵,但是关于替换的后半部分我遇到了问题。

我是一个初学者,现在只学习了几个月的python(这就是为什么我的以下代码可能读起来很痛苦)。非常感谢您的任何帮助!

正在读取的文件包含以下内容:

###########
      # # #
# ### # # #
# #   # # #
# ##### # #
#       # #
# ####### #
# #       #
# ####### #
#          
###########

这是我的代码:

def loadmaze(filename):
    f = open(filename)
    lines = f.readlines()
    COR = "0"
    WALL = "-1"
    MINO = "2"
    new_maze = []
    for i in range(len(lines)):
        lines[i] = "*" + lines[i]
        lines[i] = lines[i].strip("*").strip("n")
        new_maze.append(lines[i])
    x = new_maze
    con_maze = []
    for i in range(len(x)):
        z = list(x[i])
        con_maze.append(z)
    for i in range(len(con_maze)):
        for j in range(len(con_maze[i])):
            con_maze[i][j].replace("'#'", COR)
            con_maze[i][j].replace(" ", WALL)
            con_maze[i][j].replace("M", MINO)
    return con_maze
print loadmaze("maze.txt")
import re
from pprint import pprint
def loadmaze(filename):
    maze = []
    with open(filename) as f:
        for line in f:
            with_delimiters = ''
            for i,ch in enumerate(line):
                with_delimiters += 'S' + ch
            line = with_delimiters
            inchars = '# M'
            outchars = ['-1','0','-2']
            for i,ch in enumerate(inchars):
                line = line.replace(ch,outchars[i])
                line = line.replace('n','')
            maze_col = line.split('S')
            for i in maze_col:  
                if i == '':
                    maze_col.remove(i)
            maze.append(map(int,maze_col))
    return maze

pprint (loadmaze('maze.txt'))

输出:

[[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
 [0, 0, 0, 0, 0, 0, -1, 0, -1, 0, -1],
 [-1, 0, -1, -1, -1, 0, -1, 0, -1, 0, -1],
 [-1, 0, -1, 0, 0, 0, -1, 0, -1, 0, -1],
 [-1, 0, -1, -1, -1, -1, -1, 0, -1, 0, -1],
 [-1, 0, 0, 0, 0, 0, 0, 0, -1, 0, -1],
 [-1, 0, -1, -1, -1, -1, -1, -1, -1, 0, -1],
 [-1, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1],
 [-1, 0, -1, -1, -1, -1, -1, -1, -1, 0, -1],
 [-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]]

相关内容

  • 没有找到相关文章

最新更新