zoukankan      html  css  js  c++  java
  • 如何用python批量翻译文本?

    首先,看一下百度翻译的官方api文档。

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

    # coding=utf-8
    #authority:bing
    #2017-7-18
    import httplib
    import md5
    import urllib
    import urllib2
    import random
    # import sys
    # reload(sys)
    # sys.setdefaultencoding('utf8')
    #
    appid = '20151113000005349'
    secretKey = 'osubCEzlGjzvw8qdQc41'
    
    httpClient = None
    myurl = '/api/trans/vip/translate'
    f = open("1.csv", 'r')
    q = f.read(20000)#最多读这么多,再多点就会出问题。
    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()
    
        cc = response.read()
        ccc = cc.decode("unicode_escape")
        ccc = ccc.encode("utf-8")
        file_object = open('thefile.txt', 'w')
        file_object.write(ccc)
        file_object.close()
    except Exception, e:
        print e
    finally:
        if httpClient:
            httpClient.close()
    f.close()

    文件怎么上传的?现在有点忙,以后再解决!!!!

    1.csv 里面每一行是需要翻译的文本

  • 相关阅读:
    redis介绍
    多线程学习
    hashMap,hashTable,TreeMap,concurrentHashMap区别
    HashMap实现原理
    ArrayList,LinkedList,Vector区别.TreeSet,TreeSet,LinkedHashSet区别
    List与Set区别
    转:java身份证格式强校验
    RedisUtil: Jedis连接自动释放
    MySQL 相邻两条数据相减
    java 将byte[]转为各种进制的字符串
  • 原文地址:https://www.cnblogs.com/xubing-613/p/7201350.html
Copyright © 2011-2022 走看看