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("\n  input word to translate ,#[ input \"!\"exit ]\n>")

            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 .\translate_word_new.py %1

pause

posted on 2017-05-30 22:43  MorePower  阅读(1365)  评论(0编辑  收藏  举报

导航