• 利用Python实现百度API的调用


    1。先要注册百度API成为开发者,

    下面是开发者申请链接:

    http://api.fanyi.baidu.com/api/trans/product/index

    为方便使用,百度翻译开放平台提供了详细的接入文档,链接如下:

    http://api.fanyi.baidu.com/api/trans/product/apidoc

    在翻译文档中列出了详细的使用方法,以下是接入文档原文:

    例:将apple从英文翻译成中文:

    请求参数:

    q=apple

    from=en

    to=zh

    appid=2015063000000001

    salt=1435660288

    平台分配的密钥: 12345678

    生成sign:

    >拼接字符串1

    拼接appid=2015063000000001+q=apple+salt=1435660288+密钥=12345678

    得到字符串1 =2015063000000001apple143566028812345678

    >计算签名sign(对字符串1做md5加密,注意计算md5之前,串1必须为UTF-8编码)

    sign=md5(2015063000000001apple143566028812345678)

    sign=f89f9594663708c1605f3d736d01d2d4

    完整请求为:

    http://api.fanyi.baidu.com/api/trans/vip/translate?q=apple&from=en&to=zh&appid=2015063000000001&salt=1435660288&sign=f89f9594663708c1605f3d736d01d2d4

    签名sign的生成

    通过Python提供的hashlib模块中的hashlib.md5()可以实现签名计算

    以接入文档中的字符串为例:

    1. import hashlib 
    2. m = '2015063000000001apple143566028812345678'  
    3. m_MD5 = hashlib.md5(m)  
    4. sign = m_MD5.hexdigest()  
    5. print 'm = ',m  
    6. print 'sign = ',sign 

    得到签名之后,按照接入文档中要求,生成URL请求,提交后可返回翻译结果。以下是接入文档提供的字段以及对应描述的截图:

    {"from":"en","to":"zh","trans_result":[{"src":"apple","dst":"u82f9u679c"}]} 

    解析返回结果

    提交URL后的返回值为json格式,使用json模块可以对结果进行解析:

    1. import json  
    2. result = '{"from":"en","to":"zh","trans_result":[{"src":"apple","dst":"u82f9u679c"}]}'  
    3. data = json.loads(result)  
    4. print data['trans_result'][0]['dst']  

    以上就是API调用的所有程序。

    --------------------------------------------------------------------------------------------------------------------------------------------------------------

    官方给定的demo,经验证,可执行。

    # -*- coding:utf-8 -*-
    import httplib
    import md5
    import urllib
    import random
    import codecs

    result = codecs.open('result1', 'w', encoding='utf-8')
    appid = '20170406000044276'
    secretKey = 'Q6g9YuaGq8Cqp0vnu2Cj'

    httpClient = None
    myurl = '/api/trans/vip/translate'
    q = 'My name is Xiaobing.'
    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()
    sentence = response.read()
    print sentence.decode('unicode_escape')
    #print sentence.encode('utf-8')
    result.write(sentence.decode('unicode_escape'))
    except Exception, e:
    print e
    finally:
    if httpClient:
    httpClient.close()
    result.close()
    ---------------------------------------重新安装了Python版本3.6.2之后,因为Python的不兼容性,代码改为如下---------------------
    import http.client
    import hashlib
    import json
    import urllib
    import random


    def baidu_translate(content):
    appid = '20170406000044276'
    secretKey = 'Q6g9YuaGq8Cqp0vnu2Cj'
    httpClient = None
    myurl = '/api/trans/vip/translate'
    q = content
    fromLang = 'en' # 源语言
    toLang = 'zh' # 翻译后的语言
    salt = random.randint(32768, 65536)
    sign = appid + q + str(salt) + secretKey
    sign = hashlib.md5(sign.encode()).hexdigest()
    myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(
    q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
    salt) + '&sign=' + sign

    try:
    httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
    httpClient.request('GET', myurl)
    # responseHTTPResponse对象
    response = httpClient.getresponse()
    jsonResponse = response.read().decode("utf-8") # 获得返回的结果,结果为json格式
    js = json.loads(jsonResponse) # json格式的结果转换字典结构
    dst = str(js["trans_result"][0]["dst"]) # 取得翻译后的文本结果
    print(dst) # 打印结果
    except Exception as e:
    print(e)
    finally:
    if httpClient:
    httpClient.close()


    if __name__ == '__main__':
    while True:
    print("请输入要翻译的内容,如果退出输入q")
    content = input()
    if (content == 'q'):
    break
    baidu_translate(content)
    ------------------------------------------------------------------------------------------------------------------------------
    单个句子的翻译目前没什么问题 但是替换成翻译一个文档的话 究竟文档的读写应该放在哪里比较效率高?翻译一句 就请求一次吗?还是怎么。。。
    文件读写式的翻译:
    #-*- coding: utf-8 -*-
    import http.client
    import hashlib
    import json
    import urllib
    import random
    import codecs


    def baidu_translate(content):
    appid = '20170406000044276'
    secretKey = 'Q6g9YuaGq8Cqp0vnu2Cj'
    httpClient = None
    myurl = '/api/trans/vip/translate'
    q = content
    fromLang = 'zh' # 源语言
    toLang = 'en' # 翻译后的语言
    salt = random.randint(32768, 65536)
    sign = appid + q + str(salt) + secretKey
    sign = hashlib.md5(sign.encode()).hexdigest()
    myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(
    q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
    salt) + '&sign=' + sign

    try:
    httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
    httpClient.request('GET', myurl)
    # responseHTTPResponse对象
    response = httpClient.getresponse()
    jsonResponse = response.read().decode("utf-8") # 获得返回的结果,结果为json格式
    js = json.loads(jsonResponse) # json格式的结果转换字典结构
    dst = str(js["trans_result"][0]["dst"]) # 取得翻译后的文本结果
    print(dst) # 打印结果
    return dst
    except Exception as e:
    print(e)
    finally:
    if httpClient:
    httpClient.close()


    if __name__ == '__main__':
    inputFile = codecs.open("input.txt", "rb", "utf-8")
    outputFile = codecs.open("output.txt","wb","utf-8")
    for line in inputFile.readlines():
    if line.split():
    resultline = ''
    content = line.split()
    if content == 'q':
    break
    resultline = baidu_translate(str(content))
    outputFile.write(resultline + " ")
     
  • 相关阅读:
    一个强迫症用户的锤子手机使用体验
    起点——2015年终总结
    用“MEAN”技术栈开发web应用(三)用mongodb搭建数据库
    用“MEAN”技术栈开发web应用(二)express搭建服务端框架
    SpringBoot/Spring使用@Value进行属性绑定(尚硅谷)
    springboot/spring使用ConfigurationProperties注解读取自定义属性(尚硅谷)
    Spring Boot项目中@SpringBootTest测试的时候卡住,一直Resolving Maven dependencies...
    ASP.NET项目:请使用语言版本6或者更高版本
    安装CUDA坑:CUDA driver version is insufficient for CUDA runtime version
    Failed to load the native TensorFlow runtime. ImportError: libcuda.so.1: cannot open shared object file: No such file or directory
  • 原文地址:https://www.cnblogs.com/maowuyu-xb/p/9075635.html
Copyright © 2020-2023  润新知