• python使用百度翻译api


    python使用百度翻译  http://api.fanyi.baidu.com/api/trans/product/apidoc

    没有appid ,secretKey  先去申请.

    也可使用get请求参考demo

    import hashlib
    import json
    import random
    import requests
    
    
    url="http://api.fanyi.baidu.com/api/trans/vip/translate"
    appid = '2018100100022222'  # 你的appid
    secretKey = 'xsdfvDIo0j2bpRFfaSWxavx5'  # 你的密钥
    salt = random.randint(32768, 65536)
    
    def get_tra_res(q,fromLang='cht',toLang='en'):
    #生成签名
        sign = appid + q + str(salt) + secretKey
        sign = hashlib.md5(sign.encode()).hexdigest()
    #post请求参数
        data = {
            "appid": appid,
            "q": q,
            "from": fromLang,
            "to" : toLang,
            "salt" : str(salt),
            "sign" : sign,
        }
    #post请求
        res = requests.post(url, data=data)
    #返回时一个json
        trans_result = json.loads(res.content).get('trans_result')[0].get("dst")
        return trans_result
    #/usr/bin/env python
    #coding=utf8
    
    import httplib
    import md5
    import urllib
    import random
    
    appid = '' #你的appid
    secretKey = '' #你的密钥
    
    
    httpClient = None
    myurl = '/api/trans/vip/translate'
    q = 'apple'
    fromLang = 'en'
    toLang = 'zh'
    salt = random.randint(32768, 65536)
    
    sign = appid+q+str(salt)+secretKey
    m1 = md5.new()
    m1.update(sign)
    sign = m1.hexdigest()
    myurl = myurl+'?appid='+appid+'&q='+urllib.quote(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign
    
    try:
        httpClient = httplib.HTTPConnection('api.fanyi.baidu.com')
        httpClient.request('GET', myurl)
    
        #response是HTTPResponse对象
        response = httpClient.getresponse()
        print response.read()
    except Exception, e:
        print e
    finally:
        if httpClient:
            httpClient.close()
  • 相关阅读:
    JDBC初体验
    Linux的常用命令--文件的相关操作
    Spring框架之AOP的基本配置
    坦克大战系列7-策略分析之扫描策略和移动策略
    坦克大战系列8-策略分析之瞄准策略
    CF846F Random Query
    CF388C Fox and Card Game
    CF1097F Alex and a TV Show
    CF1276C Beautiful Rectangle
    [SDOI2016]征途
  • 原文地址:https://www.cnblogs.com/wdee/p/9878658.html
Copyright © 2020-2023  润新知