我需要解碼,使用Python 3,經編碼方式如下字符串:如何解碼dtype = numpy.string_的numpy數組?
>>> s = numpy.asarray(numpy.string_("hello\nworld"))
>>> s
array(b'hello\nworld',
dtype='|S11')
我想:
>>> str(s)
"b'hello\\nworld'"
>>> s.decode()
AttributeError Traceback (most recent call last)
<ipython-input-31-7f8dd6e0676b> in <module>()
----> 1 s.decode()
AttributeError: 'numpy.ndarray' object has no attribute 'decode'
>>> s[0].decode()
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-34-fae1dad6938f> in <module>()
----> 1 s[0].decode()
IndexError: 0-d arrays can't be indexed
謝謝!這有很大幫助。現在我可以通過這種方式恢復我的字符串:'s = str(s.astype(str))' – PiRK
當你可以直接用'unicode_'獲得常規字符串時,不需要轉換類型。 – Kasramvd
我不控制編碼階段。在我現實世界的問題中,我自己並沒有創造's'。我只是碰巧知道它在編碼階段後寫入了一個文件。 – PiRK