An Error: 'Numpy.str_' object has no attribute 'decode' - python

I tried to run a test on Crab(an open source recommender system) based on python3. Then an error occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/Dennis/anaconda/lib/python3.5/site-packages/scikits/crab/datasets/base.py", line 201, in load_sample_movies
data_songs[u_ix][i_ix] = float(rating)
ValueError: could not convert string to float: "b'3.0'"
I tried to use 'decode()' to convert the string, but it's not working:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/Dennis/anaconda/lib/python3.5/site-packages/scikits/crab/datasets/base.py", line 202, in load_sample_movies
rating = rating.decode('utf-8')
AttributeError: 'numpy.str_' object has no attribute 'decode'
Any help will be appreciated!

The problem is that rating is a string within a string, so when you try casting a string like "b'3.0'" into a float, it gives a valueError because you still have the b in front which cannot be converted into float.
I imagine you need the byte encoding in front of the '3.0', so one way would be to evaluate rating to convert it from a string to bytes before typecasting it into a float (beware though, eval can have some safety issues).
>>> type(eval(rating))
<class 'bytes'>
>>> data_songs[u_ix][i_ix] = float(eval(rating))

Related

Order of Exception evaluations

In python exceptions, does the TypeError check occur before doing the ValueError check? For example:
>>> chr(123)
'{'
>>> chr('x')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required (got type str)
>>> chr(18293939)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: chr() arg not in range(0x110000)
>>> chr(1829393993939393)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: signed integer is greater than maximum
Or what is the order in which the various errors are checked? Is there documentation on the order of operations/evaluations for the difference Exception types?
None of this is documented (i.e., guaranteed). That said, it would be impossible to raise a sensible ValueError if there was no value of the correct type to compare. The difference between ValueError and OverflowError is surely an implementation detail entirely, since anything that overflows the target type would of course be out of any restricted range for that type.

Not able to open and load pickle file in python 3.6.1

I am trying to open and load pickle file but by two ways. But every time I am getting an error.
Request you to please help.
First way :
enron_data = pickle.load(open("D:/New/ud120-projects/final_project/final_project_dataset.pkl", "r"))
Error: Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
Second Way :
enron_data = pickle.load(open("D:/New/ud120-projects/final_project/final_project_dataset.pkl", "rb"))
Error : Traceback (most recent call last):
File "<stdin>", line 1, in <module>
_pickle.UnpicklingError: the STRING opcode argument must be quoted
Request you to please help
If you are on Windows you have to use a raw string and backslashes like this:
r'D:\path\to\your\file'

Splitting strings unhashable type

I have never split strings in Python before so I am not too sure what is going wrong here.
import pyowm
owm = pyowm.OWM('####################')
location = owm.weather_at_place('Leicester, uk')
weather = location.get_weather()
weather.get_temperature('celsius')
temperature = weather.get_temperature('celsius')
print(temperature[5:10])
Error received
sudo python weather.py
Traceback (most recent call last):
File "weather.py", line 10, in <module>
print(temperature[5:10])
TypeError: unhashable type
get_temperature returns a dictionary, which you're then trying to index with a slice object, which is not hashable. e.g.
>>> hash(slice(5, 10))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type
To get the temperature, you need to get it from the dictionary like this:
temperature['temp']

Possible Bug in codecs.decode using ROT13

Python 3.5.1 on Ubuntu
>>> from codecs import decode
>>> s = 'string'
>>> b = b'bytes'
>>> decode(b, 'utf8')
'bytes'
>>> decode(s, 'utf8')
Traceback (most recent call last):
File "/usr/lib/python3.5/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
TypeError: a bytes-like object is required, not 'str'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: decoding with 'utf8' codec failed (TypeError: a bytes-like object is required, not 'str')
so far everything behaves as expected. But when I try to use ROT13 encoding I get:
>>> decode(s, 'rot13')
'fgevat'
>>> decode(b, 'rot13')
Traceback (most recent call last):
File "/usr/lib/python3.5/encodings/rot_13.py", line 18, in decode
return (input.translate(rot13_map), len(input))
TypeError: a bytes-like object is required, not 'dict'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: decoding with 'rot13' codec failed (TypeError: a bytes-like object is required, not 'dict')
As #snakecharmerb points out ROT13 en/decoding is only supposed to work on strings.
The exception Message though, is still wrong since it states, that a bytes-like object was expected even when a bytes-like object was actually passed, and mentions some dictionary the user did not create.
Regarding the ROT13 codec, the Python 3.5 docs state:
The following codec provides a text transform: a str to str mapping.
It is not supported by str.encode() (which only produces bytes
output).
that is, you can only pass unicode strings (str objects) when encoding to ROT13 and you will only get str objects back.
This is different from Python 2.x, when ROT13 was treated the same as other codecs. ROT13 was not ported to Python 3 initially, because ROT13 does not encode a unicode string to bytes - it just swaps letters around. It as reinstated, as a text transform in Python 3.2 and 3.4. The full story is in this bug report.

pickle, 'str' does not support buffer interface in python

Ok so I have the following code:
def rate_of_work(self):
global rate
rate = (turtle.textinput("Your Work Rate","What is your hourly work rate in US Dollars?"))
outFile_rate = pickle.dumps(rate)
rate1 = pickle.loads(rate)
rate2 = ((hours*rate1) + (minutes*rate1)*0.0167 + (seconds*rate1)*0.000278) #isnt necessary information
rate3 = round(rate2, 2) #isnt necessary information
im getting the error:
rate1 = pickle.loads(rate)
TypeError: 'str' does not support the buffer interface
please help
I assume you are working under python 3.x
For the specific error, pickle.loads() only accepts bytes, and you are trying to give a plain string to it, that's why it fails.
>>> pickle.loads("")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' does not support the buffer interface
>>> pickle.loads(b"")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
EOFError

Categories