python简易翻译器的运行
Python3.6实现带有简单界面的有道翻译小程序本人使用的是python3.6(32bit),在win10上运行的
代码如下:
|
from tkinter import * import urllib.request import urllib.parse import json #实现翻译功能的函数 def translate(content): url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionfrom=dict2.index' #第一种方法 #head必须是字典类型的参数 head = {} head[ 'user-agent' ] = 'mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/55.0.2883' data = {} data[ 'type' ] = 'auto' data[ 'i' ] = content data[ 'doctype' ] = 'json' data[ 'xmlversion' ] = '1.8' data[ 'keyfrom' ] = 'fanyi.web' data[ 'ue' ] = 'utf-8' data[ 'action' ] = 'fy_by_clickbutton' data[ 'typoresult' ] = 'true' data = urllib.parse.urlencode(data).encode( 'utf-8' ) req = urllib.request.request(url,data,head) response = urllib.request.urlopen(req) html = response.read().decode( 'utf-8' ) target = json.loads(html) result = target[ 'translateresult' ][ 0 ][ 0 ][ 'tgt' ] return result #实现界面功能 root = tk() root.title( '中英互译' ) frame = frame(root) frame.grid(padx = 10 , pady = 10 ) v2 = stringvar() label(frame,text = '输入要翻译的文字:' ).grid(row = 0 ,column = 0 ) label(frame,text = '翻译之后的结果:' ).grid(row = 5 ,column = 0 ) e1 = entry(frame) e1.grid(row = 0 , column = 1 ) e2 = entry(frame, textvariable = v2, state = 'readonly' )\ .grid(row = 5 , column = 1 ) def trans(): r = translate(e1.get()) v2. set (r) #print(r) button(root,text = '翻译' ,width = 10 ,command = trans)\ .grid(row = 10 ,column = 0 ,sticky = w) button(root,text = '退出' ,width = 10 ,command = root.quit)\ .grid(row = 10 ,column = 1 ,sticky = e) mainloop() |
总结
以上所述是小编给大家介绍的python3.6实现带有简单界面的有道翻译小程序,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对开心学习网网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢原文链接:https://blog.csdn.net/bjxdbz/article/details/73863552