我有一个类似这样的numpy二进制数组:
np_bin_array = [0 1 0 0 1 0 0 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 0 0 0 1 1 0 1 1 0 0 0 1 1 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
这是一个8位字符串,从左边开始填充0。
我需要将其转换回字符串,以重新形成单词,并去除0,输出应为“Hello”。
谢谢你的帮助!
numpy.packbits()
将位解释为数组,然后通过应用bytearray()
将其转换为字节数组,最后使用 decode()
使其成为普通字符串。
下面是代码:
import numpy
np_bin_array = [0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
print(bytearray(numpy.packbits(np_bin_array)).decode().strip("\x00"))
提供
Hello
这个对我有用。不过我原本是一个布尔数组,所以需要进行额外的转换。
def split_list(alist,max_size=1):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(alist), max_size):
yield alist[i:i+max_size]
result = "".join([chr(i) for i in (int("".join([str(int(j)) for j in letter]), base=2) for letter in split_list(np_bin_array, 8)) if i != 0])
import numpy as np
np_bin_array = np.array([0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
bhello = ''.join(map(str, np_bin_array))
xhello = hex(int(bhello, 2)).strip("0x")
''.join(chr(int(xhello[i:i+2], 16)) for i in range(0, len(xhello), 2))
我用以下代码使其正常工作:
np_bin_array = [0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
yy=[]
yy_word=""
yy=np.packbits(np_bin_array)
for i in yy:
if i:
j = chr(i)
yy_word += str(j)
print(yy_word)
np_bin_array
是如何生成的信息吗?我用一个简单的布尔型numpy数组无法重现这个问题,我猜你指的是其他什么东西? - Chazeon