NumPy `fromstring`函数在Python 2.7中工作正常,但在Python 3.7中返回错误

7xllpg7q  于 12个月前  发布在  Python
关注(0)|答案(3)|浏览(71)

我使用以下语法转换字节数组数据字(每个样本2个字节):

data = numpy.fromstring(dataword, dtype=numpy.int16)

Python 3.7中的相同指令返回错误:

TypeError: fromstring() argument 1 must be read-only bytes-like object, not memoryview

dataword = scope.ReadBinary(rlen-4) #dataword is a byte array, each 2 byte is an integer
data = numpy.fromstring(dataword, dtype=numpy.int16)# data is the int16 array

以下是Python 2.7.14中data的内容:

[-1.41601562 -1.42382812 -1.42578125 ...,  1.66992188  1.65234375  1.671875  ]

我希望在Python 3.7中得到同样的结果。
在Python 3.7中如何使用numpy.fromstring()

bxfogqkk

bxfogqkk1#

TypeError试图告诉您dataword是不受支持的类型memoryview
它需要作为不可变类型传递,如bytes

data = numpy.fromstring(dataword.tobytes(), dtype=numpy.int16)

甚至更好; scope似乎是一个类似于文件的对象,所以这也可以工作:

data = numpy.fromfile(scope, dtype=numpy.int16, count=rlen//2-4)
r8xiu3jd

r8xiu3jd2#

简单的解决方案发现阅读numpy手册:用frombuffer替换fromstring
data = numpy.frombuffer(dataword,dtype=numpy.int16)运行良好

ix0qys7i

ix0qys7i3#

fromstring不起作用,因为dataword是一个memeoryview而不是一个字符串,那么必须使用frombuffer
data = numpy.frombuffer(dataword.tobytes(), dtype=numpy.int16)

相关问题