实现原理
tkinter 设计图形交互界面
在百度开发者平台申请权限 获得 appid 密钥
为保证安全 要使用 sign签名:使用md5算法 生成的一段字符串 生成的签名长度为32位 英文字符均为小写格式
签名生成的方法:
将请求参数中的 aappid+query(q,注意为'utf-8'编码)+salt(随机数)+密钥 得到字符串l
再将 l做md5 得到32位小写的sign
注意:
1.先将需要翻译的文本转换为'utf-8'编码
2.在发送HTTP请求前对各字段做URL encode
3.在生成签名拼接字符串时 q不用做URL encode 在生成签名之后发送HTTP 之前才需要对要发送的待翻译文本q做URL encode
# 简易源码
import hashlib
import random
import urllib
from urllib import *
from urllib import parse
import json
import http
from http import client
import tkinter
def baiduTranslate(translate_text, flag=1):
'''
:param translate_text: 待翻译的句子,len(q)<2000
:param flag: 1:原句子翻译成英文;0:原句子翻译成中文
:return: 返回翻译结果。
For example:
q=我今天好开心啊!
result = {'from': 'zh', 'to': 'en', 'trans_result': [{'src': '我今天好开心啊!', 'dst': "I'm so happy today!"}]}
'''
appid = '20230219001567806' # 填写你的appid
secretKey = 'qhtfvJ6U5aXBTI5oghQN' # 填写你的密钥
httpClient = None
myurl = '/api/trans/vip/translate' # 通用翻译API HTTP地址
fromLang = 'auto' # 原文语种
if flag:
toLang = 'en' # 译文语种
else:
toLang = 'zh' # 译文语种
salt = random.randint(3276, 65536)
sign = appid + translate_text + str(salt) + secretKey
sign = hashlib.md5(sign.encode()).hexdigest()
myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(translate_text) + '&from=' + fromLang + \
'&to=' + toLang + '&salt=' + str(salt) + '&sign=' + sign
# 建立会话,返回结果
try:
httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
httpClient.request('GET', myurl)
# response是HTTPResponse对象
response = httpClient.getresponse()
result_all = response.read().decode("utf-8")
result = json.loads(result_all)
# return result
return result['trans_result'][0]['dst']
except Exception as e:
print(e)
finally:
if httpClient:
httpClient.close()
if __name__ == '__main__':
# 手动录入翻译内容,q存放
# q = raw_input("please input the word you want to translate:")
q = "听我说谢谢你!"
'''
flag=1 输入的句子翻译成英文
flag=0 输入的句子翻译成中文
'''
result = baiduTranslate(q, flag=1) # 百度翻译
print("原句:"+q)
print(result)
# tkinter 图形界面版
import hashlib
import random
import urllib
from urllib import *
from urllib import parse
import json
import http
from http import client
import tkinter
from tkinter import *
def baiduTranslate(translate_text, flag=1):
'''
:param translate_text: 待翻译的句子,len(q)<2000
:param flag: 1:原句子翻译成英文;0:原句子翻译成中文
:return: 返回翻译结果。
For example:
q=我今天好开心啊!
result = {'from': 'zh', 'to': 'en', 'trans_result': [{'src': '我今天好开心啊!', 'dst': "I'm so happy today!"}]}
'''
appid = '@@@' # 填写你的appid
secretKey = '@@@' # 填写你的密钥
httpClient = None
myurl = '/api/trans/vip/translate' # 通用翻译API HTTP地址
fromLang = 'auto' # 原文语种
if flag:
toLang = 'jp' # 译文语种
else:
toLang = 'zh' # 译文语种
salt = random.randint(3276, 65536)
sign = appid + translate_text + str(salt) + secretKey
sign = hashlib.md5(sign.encode()).hexdigest()
myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(translate_text) + '&from=' + fromLang + \
'&to=' + toLang + '&salt=' + str(salt) + '&sign=' + sign
# 建立会话,返回结果
try:
httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
httpClient.request('GET', myurl)
# response是HTTPResponse对象
response = httpClient.getresponse()
result_all = response.read().decode("utf-8")
result = json.loads(result_all)
# return result
return result['trans_result'][0]['dst']
except Exception as e:
print(e)
finally:
if httpClient:
httpClient.close()
def leftClick1(event):
ch_str = Entry1.get()
print("要翻译的内容:",ch_str)
result = baiduTranslate(ch_str,flag=1)
print("翻译后的结果为:",result)
s.set('')
s.set(result)
# Entry2.insert(0,result)
def leftClick2(event):
s.set('')
Entry1.delete(0,'end')
if __name__ == '__main__':
# 手动录入翻译内容,q存放
# q = raw_input("please input the word you want to translate:")
root = Tk()
root.geometry('250x130')
root.title('U-L-G-A-N-O-Y')
Label(root , text='Input Text',width=15).place(x=1,y=1)
Label(root , text='Result',width=15).place(x=1,y=20)
Entry1 = Entry(root , width=20)
Entry1.place(x=110,y=1)
s = StringVar()
Entry2 = Entry(root , width=20,textvariable=s)
Entry2.place(x=110,y=20)
Button1 = Button(root , text='Translate',width=8)
Button2 = Button(root , text='Clear',width=8)
Button1.place(x=40,y=80)
Button2.place(x=110,y=80)
# 绑定监听
Button1.bind("<Button-1>",leftClick1)
Button2.bind("<Button-1>",leftClick2)
root.mainloop()
有点写麻了的kimoji…
清空Entry 输入框 Entry1.delete(0,'end')
注意其中 html库 建立请求的方法
注意 string.decode('utf-8')
注意json.loads()将xxx格式转换为str的应用!!!