[英]How to read a file in python and save its content to a two dimensional array?
In python I need to read a txt file that consists a maze made of A (start point), B (end point), spaces (for no wall) and * (for wall). 在python中,我需要读取一个包含由A(起点),B(终点),空格(无墙)和*(墙)构成的迷宫的txt文件。 Here is a picture how it could look like:
这是一张图片,看起来像是这样的:
*************
*A* * * *
* * * * * * *
* * * * *
* * * * ** *
* * * B*
*************
I need to create a function that reads this file and returns an two dimensional array (numpy library) that consists the content of the txt file (0 for a wall, 1 for a space, 2 for value A and 3 for value B). 我需要创建一个读取此文件并返回二维数组(numpy库)的函数,该数组包含txt文件的内容(0表示墙,1表示空格,2表示值A,3表示值B)。 In the other part of the array should be the column.
在数组的另一部分应该是列。 How am I doing this?
我怎么做的?
I got so far: 我到目前为止:
import numpy 导入numpy
def read_file:
f = open("file.txt", "r")
line = f.readline()
array = numpy.zeros((line, line.split()), dtype=int)
f.close()
return array
With that I get an error: type error, object can not be interpreted as an integer.What am I doing wrong? 有了这个我得到一个错误:类型错误,对象不能被解释为一个整数。我做错了什么?
How do I realize this? 我怎么知道这个?
You could use a dict. 你可以用dict。 I haven't tested the following code, but I think this would work.
我没有测试过以下代码,但我认为这样可行。
Edit: I realized that the numpy array was going to be a flat vector instead of 2 dimensional and I adjusted the code to address this problem. 编辑:我意识到numpy数组将是一个平面向量而不是2维,我调整代码来解决这个问题。
def read_file(file):
# dict storing replacements
code = {'*':0,' ':1,'A':2,'B':3}
f = open(file, "r")
s = f.read()
f.close()
lines = s.split('\n')
# get a list of lists with each character as a separate element
maze = [list(line) for line in lines]
# Get the dimensions of the maze
ncol = len(maze[0])
nrow = len(maze)
# replace the characters in the file with the corresponding numbers
maze = [code[col] for row in maze for col in row]
# convert to numpy array with the correct dimensions
maze = numpy.array(maze).reshape(nrow,ncol)
return(maze)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.