我编写了一个基本脚本,通过numpy生成一个33到255之间整数的方形矩阵在python3中生成。我可以很容易地达到这一点,但问题是下一个: 我尝试用方形矩阵中的ASCII符号转换这个数字。但在Internet或StackOver Flow中搜索后,我找不到解决方案。这是我的代码:
#!usr/bin/env/python3.6
# imports
import numpy as np
import random
# Generated random matrix of 25 spaces,
# where placed ramdom number between 0 to 255,
# and store in a variable.
matrix = np.random.randint(33,255, size=(5, 5))
# This shows the matrix of integer numbers.
print(matrix) # Good!!!
# This translate matrix of number to ASCII table symbols:
for matrix in store:
print(chr(matrix)) # BANG! Error, my honey.
答案 0 :(得分:1)
这个
dtype = np.uint16 if np.dtype('U1').itemsize==2 else np.uint32
matrix.astype(dtype).view('U1')
array([['Ö', '´', 'O', 'i', '\x98'],
['à', 'ü', 'S', 'm', 'æ'],
['ý', 'm', '#', 'ö', 'u'],
['±', 'l', '\x82', 'O', 'È'],
['h', '&', '\x82', 'ª', '\xad']],
dtype='<U1')
有点作品。但是,不是100%确定它的ASCII。但它与chr
:
import pprint
>>> pprint.pprint([[chr(number) for number in row] for row in matrix])
[['Ö', '´', 'O', 'i', '\x98'],
['à', 'ü', 'S', 'm', 'æ'],
['ý', 'm', '#', 'ö', 'u'],
['±', 'l', '\x82', 'O', 'È'],
['h', '&', '\x82', 'ª', '\xad']]
我们正在做的是首先转换为uint16
或uint32
,因为U
dtype似乎每个字符有2或4个字节。然后,我们将视图转换为U1
,将数字重新解释为字符及其字符。
答案 1 :(得分:1)
代码中的store
是什么。修复此错误后,它可以正常工作
#!usr/bin/env/python3.6
# imports
import numpy as np
import random
# Generated random matrix of 25 spaces,
# where placed ramdom number between 0 to 255,
# and store in a variable.
matrix = np.random.randint(33,255, size=(5, 5))
# This shows the matrix of integer numbers.
print(matrix) # Good!!!
# This translate matrix of number to ASCII table symbols:
for col in range(5):
for row in range(5):
print(chr(matrix[row][col]), end=' ')
print('\n') # Solved, my honey.
输出是 -
[[ 86 159 40 221 211]
[166 224 213 252 160]
[155 160 111 109 164]
[ 98 190 34 250 40]
[115 228 59 139 221]]
V ¦ b s
à ¾ ä
( Õ o " ;
Ý ü m ú
Ó ¤ ( Ý