Last active
December 4, 2019 07:50
-
-
Save yyq/427fd8badde5667c4e4d88cf6f2d3f30 to your computer and use it in GitHub Desktop.
百度翻译api示例代码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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