python 百度翻译API的示例代码
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 百度翻译API的示例代码相关的知识,希望对你有一定的参考价值。
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""readme
this script is python 3 only
please config your own appid and secretKey, refer link: http://api.fanyi.baidu.com/api/trans/product/index
usage command: python translate-baidu-api.py word.txt
translate result will be stdout line by line
"""
import http.client as httplib
import hashlib
import urllib
import random
import sys
def translate(transchar):
appid = 'xxxxxxxxxxxxx'
secretKey = 'yyyyyyyyyyyy'
httpClient = None
myurl = '/api/trans/vip/translate'
q = transchar
fromLang = 'zh'
toLang = 'en'
salt = random.randint(32768, 65536)
sign = appid+q+str(salt)+secretKey
# m1 = md5.new()
# m1.update(sign)
# sign = m1.hexdigest()
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 = httplib.HTTPConnection('api.fanyi.baidu.com')
httpClient.request('GET', myurl)
# response是HTTPResponse对象
response = httpClient.getresponse()
answer = response.read().decode("utf-8")
# print(type(answer))
answer = answer.split('dst')[1]
answer = answer.replace('\"', '')
answer = answer.replace(':', '')
answer = answer.replace('}', '')
answer = answer.replace(']', '')
return transchar + "#===#" + answer
except(Exception, e):
print(e)
finally:
if httpClient:
httpClient.close()
with open(sys.argv[1]) as f:
for word in f:
print(translate(word.strip()))
以上是关于python 百度翻译API的示例代码的主要内容,如果未能解决你的问题,请参考以下文章
小白学Python——用 百度翻译API 实现 翻译功能
用python实现百度翻译
python学习日记-百度翻译GUI
python 有道,腾讯,谷歌,百度四大翻译API聚合接口[蟒实现]
利用Python实现百度API的调用
python调用百度api应用--小小翻译器