zoukankan      html  css  js  c++  java
  • python使用百度api翻译中英文

    python使用百度api翻译中英文

    写程序取变量名的时候,常常需要翻译单词,或者将中文翻译成英语.有道词典,必应词典都很好,可是...命令行习惯了还是觉得用在cmd里面调出程序使用起来也许会更爽.于是查了查python相关的翻译脚本.都很简单,获取网页,然后解析,没找到用requeset库的.于是自己用request库写了个.. 虽然简单,但是实用就好啦~~ 上网搜索发下百度的翻译api有demo
    稍微修改一下就可以直接使用了

    #coding=utf8
     
    import httplib
    import md5
    import urllib
    import random
    import json
    
    '''
    appid 申请 http://api.fanyi.baidu.com/api/trans/product/apiapply
    '''
    
    appid = '20151113000005349'
    secretKey = 'osubCEzlGjzvw8qdQc41'
     
    httpClient = None
     
    def requestTranslate(word,fromLang = 'en',toLang="zh"):
        salt = random.randint(32768, 65536)
        sign = appid+word+str(salt)+secretKey
        m1 = md5.new()
        m1.update(sign)
        sign = m1.hexdigest()
    
        httpClient = httplib.HTTPConnection('api.fanyi.baidu.com')
        myurl = '/api/trans/vip/translate'
        myurl = myurl+'?appid='+appid+'&q='+urllib.quote(word)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign
        httpClient.request('GET', myurl)
        #response是HTTPResponse对象
        response = httpClient.getresponse()
        result = response.read()
        ret = json.loads(result)
        print(ret["trans_result"][0]["dst"])
        httpClient.close()
    
    
    #判断首字母是否是英文字母从而判断是英译汉or汉译英
    def is_english_char(ch):
        if ord(ch) not in range(97,122) and ord(ch) not in range(65,90):
            return False
        return True
    
    
    if __name__ == '__main__':
        import sys
        word = (len(sys.argv) > 1) and sys.argv[1] or None
        queryOnce = (word != None)
    
        while True:
            try:
                if word == None:
                    word = raw_input("
      input word to translate ,#[ input "!"exit ]
    >")
    
                if word == "!":
                    break
    
                fromLang = "en"
                toLang = "zh"
                if not is_english_char(word[0]):
                    fromLang = "zh"
                    toLang = "en"
                    word = word.decode('gbk').encode('utf-8')
    
                requestTranslate(word,fromLang,toLang)
                word = None
    
                if queryOnce == True:
                    break
            except Exception,e:
                print('!!!!! catch error!! ' + str(e))
                word = None
    
    

    推荐将如下 脚本放在 环境变量里边,直接 win+r , tw english 或者 tw 中文~~
    效果更快

    @echo off
    set OLD_DIR=%cd%
    set DIR=%~dp0
    cd /d %DIR%
    
    python .	ranslate_word_new.py %1
    
    pause
    
  • 相关阅读:
    CLR Via CSharp读书笔记(26)
    RH253读书笔记(10)-Appendix A Installing Software
    RH253读书笔记(9)-Lab 9 Account Management Methods
    一位程序员工作10年总结的13个忠告
    不跟你谈“五险一金”的老板,都是在耍流氓
    RH253读书笔记(8)-Lab 8 Securing Data
    RH253读书笔记(7)-Lab 7 Electronic Mail
    RH253读书笔记(6)-Lab 6 Implementing Web(HTTP) Services
    robotium测试创建java文件和junit文件区别
    LigerUi中为Grid表加上序号,并调整适当宽度!(实例)
  • 原文地址:https://www.cnblogs.com/cheerupforyou/p/6921734.html
Copyright © 2011-2022 走看看