Keekoo77
2021-05-01 11:25
采纳率: 55.6%
浏览 36

Python3在调用有道智云文本翻译API时出现的小问题解决办法?

目标:提交编程作业

主题:制作一个翻译器

问题:报错202

我的错误代码(省去软件主体部分,只保留了需要的部分)

import time
import requests

YOUDAO_URL = 'https://openapi.youdao.com/api'
APP_KEY = '应用ID'
APP_SECRET = '应用密钥'
#Get translate word
p=input('请输入翻译词或语句:')
#About language
to='zh-CHS'#目标中文
from='en'#起始英文

#各参数 input,salt,curtime,sha256(sign),v3(signType),zh-CHS(to),en(from),q
#以下计算方法全部根据有道技术文档
if int(len(q)) >20:
    input=str[0:9]+str(len(q))+str[10:19]
    #input=q前10个字符 + q长度 + q后10个字符
    salt = str(uuid.uuid1())
    curtime = str(int(time.time()))
    sha256=APP_KEY+input+salt+curtime+APP_SECRET
    #应用ID+input+salt+curtime+应用密钥
if int(len(q)) <=20:
    #input=q字符串(当q长度小于等于20)
    input=q
    salt = str(uuid.uuid1())
    curtime = str(int(time.time()))
    sha256=APP_KEY+input+salt+curtime+APP_SECRET
data={}
data['from']=a
data['to']=b
data['signType']='v3'
data['curtime']=curtime
data['appKey']=APP_KEY
data['q']=q.encode('utf-8')
data['salt']=salt
data['sign']=sha256
response = requests.post(url=YOUDAO_URL,data=data)
print(response.json())

语法没有错误!

appkey和appsecret不方便公示,已确认正确!

参考官网:有道智云

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • Lonelypatients° 2021-05-03 09:40
    已采纳
    # -*- coding: utf-8 -*-
    import sys
    import uuid
    import requests
    import hashlib
    import time
    from imp import reload
    
    import time
    
    reload(sys)
    
    YOUDAO_URL = 'https://openapi.youdao.com/api'
    APP_KEY = '33a12299212fc28261c'
    APP_SECRET = '9PmUgMkdlJM3fLsAC3JNc4rYGXn4EgdHzgHl'
    
    
    def encrypt(signStr):
        hash_algorithm = hashlib.sha256()
        hash_algorithm.update(signStr.encode('utf-8'))
        return hash_algorithm.hexdigest()
    
    
    def truncate(q):
        if q is None:
            return None
        size = len(q)
        return q if size <= 20 else q[0:10] + str(size) + q[size - 10:size]
    
    
    def do_request(data):
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        return requests.post(YOUDAO_URL, data=data, headers=headers)
    
    
    def connect():
        q = input("待输入的文字: ")
    
        data = {}
        data['from'] = 'en'
        data['to'] = 'zh-CHS'
        data['signType'] = 'v3'
        curtime = str(int(time.time()))
        data['curtime'] = curtime
        salt = str(uuid.uuid1())
        print(q)
        signStr = APP_KEY + truncate(q) + salt + curtime + APP_SECRET
        sign = encrypt(signStr)
        data['appKey'] = APP_KEY
        data['q'] = q
        data['salt'] = salt
        data['sign'] = sign
        # data['vocabId'] = "您的用户词表ID"
    
        response = do_request(data)
        print(response.json())
    
    
    if __name__ == '__main__':
        connect()
    
    
    # 替换你的appid 和密钥就可以使用了,
    # 你demo中,因为sign 这个值你只拼接但是未通过ha256加密
    点赞 评论
  • Lonelypatients° 2021-05-01 15:41

    输入为p, 但你却又说是q, 费解...

    点赞 评论

相关推荐 更多相似问题