Boto3 和 Python3:无法将 'bytes' 对象隐式转换为 str

Boto3 and Python3: Can't convert 'bytes' object to str implicitly

我正在尝试使用 AWS Rekognition,detect_text API。我正在使用 Boto3 和 Python 3.

这是我的相关代码:

with open(file_path, 'rb') as file:
  data = file.read()

response = self._rekognition.detect_text(Image={'Bytes': data})

此代码适用于 Python2.7,但适用于 Python3。我收到以下错误:

File "...", line 39, in extract_text
response = self._rekognition.detect_text(Image={'Bytes': data})
...
...
k_date = self._sign(('AWS4' + key).encode('utf-8'),
TypeError: Can't convert 'bytes' object to str implicitly

我需要在这里更改的任何想法。

在 python 3 中,您可能需要将 bytes 转换为 str 使用。

data.decode('utf-8')

或者您可以将文本文件作为文本本身来阅读。

尝试:

with open(file_path, encoding='utf-8') as file:
  data = file.read()
response = self._rekognition.detect_text(Image={'Bytes': data})

我不知道 _rekognition.detect 接受什么,但你可以试试。