我有一个仅包含字符的字符串(尺寸:n x m)(见下文)。 Python中是否有ONE LINER(也许是numpy?)可以将此字符串转换为phyton中的二维char数组?
数据可能如下所示:
#####
#.x.#
#..y#
#####
nxm
。numpy
数组并指定 dtype='U1'
它将确保 numpy 数组中的每个元素都可以保存数据文件中的 single
字符。import numpy as np
# Read the data file and store its contents in a list
with open('data.txt', 'r') as file:
lines = file.readlines()
lines = [line.strip() for line in lines]
#dimensions of the data file
n = len(lines)
m = len(lines[0])
#Create an empty numpy array of characters with the desired dimensions
char_array = np.empty((n, m), dtype='U1')
#Iterate over each line and each character in the line, and assign the characters to the numpy array
for i in range(n):
for j in range(m):
char_array[i, j] = lines[i][j]
print(char_array)
输出-
[['#' '#' '#' '#' '#']
['#' '.' 'x' '.' '#']
['#' '.' '.' 'y' '#']
['#' '#' '#' '#' '#']]
如果我明白你在说什么,那么你可以打开并读取文件,然后解析文件的每一行以创建字符行。最后,您可以尝试将这些行存储在二维字符数组中。 例如:
file_path = "your_file.txt"
char_array = []
with open(file_path, "r") as file:
for line in file:
line = line.strip()
row = list(line)
char_array.append(row)
您可以使用
char_array[row][column]
等索引访问特定字符