Skip to content

Instantly share code, notes, and snippets.

@yyq
Last active December 4, 2019 07:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yyq/427fd8badde5667c4e4d88cf6f2d3f30 to your computer and use it in GitHub Desktop.
Save yyq/427fd8badde5667c4e4d88cf6f2d3f30 to your computer and use it in GitHub Desktop.
百度翻译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()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment