urllib2这个库 安装不了,怎么办?有没有替换文案?
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
如果您的环境无法使用 urllib2 库,也可以尝试使用 Python 内置的 requests 库来进行 HTTP 请求。
以下是使用 requests 库进行阿里云印刷文字识别服务请求的代码示例:
import requests
import json
# 阿里云 API 访问密钥
access_key_id = '<Your Access Key ID>'
access_key_secret = '<Your Access Key Secret>'
# OCR API 请求参数
params = {
'RegionId': 'cn-shanghai',
'Version': '2019-12-30',
'Method': 'POST',
'Action': 'RecognizePrintedText',
'Format': 'JSON',
'ImageURL': '',
'ImageUrl': '',
'OCRType': 'normal',
'OutputFileFormat': 'normal',
'MinHeight': '',
'MaxHeight': '',
'ReturnType': '',
'ProjectId': '',
'Side': '',
'WatermarkImageURL': '',
'Watermark': '',
}
# 图像数据
image_file = 'path/to/image.jpg'
with open(image_file, 'rb') as f:
image_data = f.read()
# HTTP POST 请求头
headers = {
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'ACS {}:{}'.format(access_key_id,
signature(params, access_key_secret))
}
# HTTP POST 请求体
data = {
'ImageType': 'Base64',
'Image': image_data.encode('base64'),
'Url': '',
'Height': '',
'Width': '',
}
# 发送 HTTP POST 请求
url = 'https://ocr.{}.aliyuncs.com/'.format(params['RegionId'])
response = requests.post(url, headers=headers, data=json.dumps(data))
# 输出识别结果
result = response.json()
print(result)
# 计算阿里云 API 访问秘钥签名
def signature(params, access_key_secret):
sorted_params = sorted(params.items(), key=lambda x: x[0])
encoded_params = '&'.join(
('='.join((k, str(v))) for k, v in sorted_params))
str_to_sign = 'POST&%2F&' + encoded_params
hmac_sha1 = hmac.new(
access_key_secret + '&', str_to_sign, hashlib.sha1).digest()
return base64.b64encode(hmac_sha1)
在以上代码中,requests 库用于进行 HTTP 请求,且使用起来更加简单方便。根据 API 文档的要求,将图像数据编码为 Base64 字符串,并将其作为 Image 参数传递给 OCR API 接口。
在 HTTP POST 请求的请求头中,需要指定 Content-Type 为 application/json 和阿里云 API 访问秘钥签名。
另外在计算阿里云 API 访问秘钥签名时,需要使用 hmac 和 hashlib 库中的加密算法和哈希算法计算签名。
用requests,https://github.com/ALIBABAOCR/OCR_EXAMPLE,此回答整理自钉群“【官方】阿里云OCR公共云客户交流群”