鱼C论坛

 找回密码
 立即注册
查看: 1979|回复: 0

[技术交流] Python小练习:TK自动有道翻译器

[复制链接]
发表于 2016-10-5 12:29:39 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
编了个自动在线翻译的翻译器(借鉴原本的TK有道翻译器,做了点修改,主要是练习为目的),省去了手动点翻译的麻烦。每3秒自动检测翻译。
但是程序好像还有个bug,就是当内容为空的时候,会报错。看看有什么好的解决方法。

自动翻译器

自动翻译器


  1. import urllib.request
  2. import urllib.parse
  3. import json
  4. import tkinter as tk
  5. root = tk.Tk()
  6. root.title('自动有道翻译器')
  7. text1 = ' '
  8. text2 = ' '

  9. def translate(sentence=' '):
  10.         if sentence != None:
  11.                 url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null'
  12.                 data = {
  13.                 "type" : "AUTO",
  14.                 "i" : sentence,
  15.                 "doctype" : "json",
  16.                 "xmlVersion" : "1.8",
  17.                 "keyfrom" : "fanyi.web",
  18.                 "ue" : "UTF-8",
  19.                 "action" : "FY_BY_CLICKBUTTON",
  20.                 "typoResult" : "true"
  21.                     }
  22.                 head = {}
  23.                 data = urllib.parse.urlencode(data).encode('utf-8')
  24.                 req = urllib.request.Request(url,data,head)
  25.                 req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36')
  26.                 response = urllib.request.urlopen(req)
  27.                 html = response.read().decode('utf-8')
  28.                 return (json.loads(html)['translateResult'][0][0]['tgt'])
  29.         else:
  30.                 translate(' ')

  31. def e1after():
  32.         global text1, text2
  33.         text2 = e1.get(1.0,tk.END)
  34.         if text2 == None or text2 == '':
  35.                 text2 = ' '
  36.         if text2 != text1:
  37.                 trans = translate(text2)
  38.                 e2['state'] = "normal"
  39.                 e2.delete(1.0,tk.END)
  40.                 e2.insert(1.0,trans)
  41.                 e2['state'] = "disabled"
  42.         else:
  43.                 pass
  44.         text1 = text2
  45.         e1.after(3000, e1after)

  46. if __name__ == '__main__':
  47.     tk.Label(root, text="需要翻译的内容:").grid(row=0, column=0)
  48.     tk.Label(root, text="翻译结果:").grid(row=2, column=0)
  49.     e1 = tk.Text(root,width=50,height=10)
  50.     e2 = tk.Text(root,width=50,height=10, state="disabled")
  51.     e1.grid(row=0, column=1, padx=10, pady=5)
  52.     e2.grid(row=2, column=1, padx=10, pady=5)
  53.     e1.insert(1.0, ' ')
  54.     e1after()
  55.     tk.mainloop()
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-25 18:45

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表