我想先将字符串转换为字节,然后将其转换为numpy数组:
utf8 string -> bytes -> numpy.array
然后:
numpy.array -> bytes -> utf8 string
下面是一个测试:
import numpy as np
string = "any_string_in_utf8: {}".format(123456)
test = np.frombuffer(bytes(string, 'utf-8'))
print(test)
这是输出:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/tmp/ipykernel_9055/3077694159.py in <cell line: 5>()
3 string = "any_string_in_utf8: {}".format(123456)
4
----> 5 test = np.frombuffer(bytes(string, 'utf-8'))
6 print(test)
ValueError: buffer size must be a multiple of element size
如何在numpy.array
和bytes
之间转换字符串
发布于 2022-07-02 12:33:45
解决办法:
Problem
中,主要的Code
是您没有提到dtype
。默认情况下,dtype
被设置为Float
,我们通常从String
启动Conversion
,这就是它抛出ValueError: buffer size must be a multiple of element size
的原因。unsigned int
,那么它就会工作,因为它不能解释Object
。欲了解更多信息,请参阅以下提供的Code Snippet
:# Import all the Important Modules
import numpy as np
# Initialize String
utf_8_string = "any_string_in_utf8: {}".format(123456)
# utf8 string -> bytes -> numpy.array
np_array = np.frombuffer(bytes(utf_8_string, 'utf-8'), dtype=np.uint8)
# Print 'np_array'
print("Numpy Array after Bytes Conversion : -")
print(np_array)
# numpy.array -> bytes -> utf8 string
result_str = np.ndarray.tobytes(np_array).decode("utf-8")
# Print Result for the Verification of 'Data Loss'
print("\nOriginal String After Conversion : - \n" + result_str)
了解更多关于np.frombuffer():- 点击这里!的信息
# Output of the Above Code: -
Numpy Array after Bytes Conversion : -
[ 97 110 121 95 115 116 114 105 110 103 95 105 110 95 117 116 102 56
58 32 49 50 51 52 53 54]
Original String After Conversion : -
any_string_in_utf8: 123456
https://stackoverflow.com/questions/72838939
复制相似问题