最近刚学习完python的基础语法,根据所列的python学习计划,学习完Python基础语法,就要学习python库,主要包含三个,即:
目前刚转战到numpy,是根据网上的博客在学习,目前遇到的问题是在执行numpy中的.frombuffer相关代码,例:
import numpy as np
s = 'Hello World'
a = np.frombuffer(s, dtype = 'S1')
print(a)
遇到了如下问题:
traceback (most recent call last):
File "D:/pyworkspace/bag learn/item.py", line 11, in <module>
a = np.frombuffer(s, dtype='S1', offset=1)
AttributeError: 'str' object has no attribute '__buffer__'
找到的解决办法是在字符串前面加上b,在PY3中,默认字符串类型是unicode。 b用于创建和显示字节串。
将第2行前面变为s = b'Hello World'就可以了,或者使用list来切分字符串,如下:
In [81]: np.array(list('hello'))
Out[81]:
array(['h', 'e', 'l', 'l', 'o'],dtype='<U1')
In [82]: np.array(b'hello')
Out[82]:
array(b'hello',dtype='|S5')
In [83]: np.array(list(b'hello'))
Out[83]: array([104, 101, 108, 108, 111])
In [85]: np.fromiter('hello','S1')
Out[85]:
array([b'h', b'e', b'l', b'l', b'o'],dtype='|S1')
In [86]: np.fromiter('hello','U1')
Out[86]:
array(['h', 'e', 'l', 'l', 'o'],dtype='<U1')*