Created
November 29, 2018 01:52
-
-
Save willwangcc/6fe9fdf5e21f05e5ae8c945f9a033bb9 to your computer and use it in GitHub Desktop.
#python #小工具 #translate
This file contains hidden or 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
#python 3.6 | |
""" | |
Reference: | |
本文代码:https://blog.csdn.net/mr_guo_lei/article/details/78617669 | |
百度官网:http://api.fanyi.baidu.com/api/trans/product/index | |
批量处理实例:https://juejin.im/entry/5bf2cebcf265da6151145aca | |
""" | |
import requests | |
import string | |
import time | |
import hashlib | |
import json | |
#init | |
api_url = "http://api.fanyi.baidu.com/api/trans/vip/translate" | |
my_appid = 你的appid | |
cyber = 你的密钥 | |
lower_case = list(string.ascii_lowercase) | |
def requests_for_dst(word): | |
#init salt and final_sign | |
salt = str(time.time())[:10] | |
final_sign = str(my_appid)+word+salt+cyber | |
final_sign = hashlib.md5(final_sign.encode("utf-8")).hexdigest() | |
#区别en,zh构造请求参数 | |
if list(word)[0] in lower_case: | |
paramas = { | |
'q':word, | |
'from':'en', | |
'to':'zh', | |
'appid':'%s'%my_appid, | |
'salt':'%s'%salt, | |
'sign':'%s'%final_sign | |
} | |
my_url = api_url+'?appid='+str(my_appid)+'&q='+word+'&from='+'en'+'&to='+'zh'+'&salt='+salt+'&sign='+final_sign | |
else: | |
paramas = { | |
'q':word, | |
'from':'zh', | |
'to':'en', | |
'appid':'%s'%my_appid, | |
'salt':'%s'%salt, | |
'sign':'%s'%final_sign | |
} | |
my_url = api_url+'?appid='+str(my_appid)+'&q='+word+'&from='+'zh'+'&to='+'en'+'&salt='+salt+'&sign='+final_sign | |
response = requests.get(api_url,params = paramas).content | |
content = str(response,encoding = "utf-8") | |
json_reads = json.loads(content) | |
print(json_reads['trans_result'][0]['dst']) | |
tests = [ | |
"I went to college in 2002.", | |
"I think i deserve a pay raise.", | |
"The customer demanded the return of the goods. ", | |
"After dinner, he offered to clean up. ", | |
"我说了算", | |
"你是猪啊?", | |
"最近过的好吗?" | |
] | |
for test in tests: | |
print(test, ":") | |
print(requests_for_dst(test)) | |
print() | |
# https://i.imgur.com/NOADmwU.png | |
# while True: | |
# word = input("输入你想翻译的内容: ") | |
# requests_for_dst(word) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment