我想先將字串轉換為位元組,然后將其轉換為 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?
uj5u.com熱心網友回復:
解決方案 :
Problem你的主要Code是你沒有提到dtype。默認情況下dtype設定為Float,我們通常Conversion從這String就是它拋出的原因開始ValueError: buffer size must be a multiple of element size。但是,如果我們將其轉換為
unsigned intthen 它將起作用,因為它無法解釋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://www.uj5u.com/ruanti/497788.html
下一篇:PIL不會加載RGB影像
