【python】AttributeError: ‘str‘ object has no attribute ‘decode‘

在跑Mask R-CNN算法时出现错误:

AttributeError: 'str' object has no attribute 'decode'

错误原因是因为python版本的问题,decoded方法一般是在python2中使用,而我的环境是基于python3的,可能是由于使用某些第三方库,该库可能包含 Python 2.x 和 Python 3.x 的兼容性问题,导致调用字符串的 decode 方法时出现错误。

解决方法有两种思路,一是将出错的语句删除;二是对python版本进行判断,执行相应正确的语句。

比如:

import sys

str_ = "Hello, World!"

if sys.version_info[0] < 3:
    # Python 2.x
    decoded_str = str_.decode('utf-8')
else:
    # Python 3.x
    decoded_str = str_

找到出错的文档找到出错的语句,我这里是这样的,由于这些变量后续还要用到,所以不能删除,因此需要对其语法作修改:

    if 'keras_version' in f.attrs:
        original_keras_version = f.attrs['keras_version'].decode('utf-8')
    else:
        original_keras_version = '1'
    if 'backend' in f.attrs:
        original_backend = f.attrs['backend'].decode('utf-8')
    else:
        original_backend = None

修改后为:

    original_keras_version = '1'
    original_backend = None
    if 'keras_version' in f.attrs:
        decoded_original_keras_version = f.attrs['keras_version']
    else:
        decoded_original_keras_version = '1'
    if 'backend' in f.attrs:
        decoded_original_backend = f.attrs['backend']
    else:
        decoded_original_backend = None

再次运行就没有错啦~

你可能感兴趣的:(python,python)