PyQT开发的简易有道词典

最近学习PyQt,写了一个比较简单的字典,使用了有道翻译OpenAPI,下面是代码:



# -*- coding: utf-8 -*-
__author__ = 'Cullen'  import urllib
import json
import urllib2
from PyQt4 import QtGui, QtCore
import sys


API_KEY = '1349304933' KEYFROM = 'cullen'  class MyDict(QtGui.QWidget):  def __init__(self):  super(MyDict, self).__init__()
      self.setGeometry(150, 150, 350, 300)
      self.setWindowTitle(u"有道字典简易版")
      self.setWindowIcon(QtGui.QIcon("./dict.png"))
      self.textEdit = QtGui.QLineEdit()
      self.searchBut = QtGui.QPushButton(u"查找")
      self.showTran = QtGui.QTextBrowser()
      grid = QtGui.QGridLayout()
      grid.addWidget(self.textEdit, 1, 0)
      grid.addWidget(self.searchBut, 1, 1)
      grid.addWidget(self.showTran, 2, 0, 1, 2)
      self.setLayout(grid)
      self.connect(self.searchBut, QtCore.SIGNAL('clicked()'),  self.get_text)


   #@QtCore.pyqtSlot()
   def get_text(self):  text = self.textEdit.text()
      if len(text) != 0:  result = get_translate(text)
         self.showTran.clear()
         self.showTran.append(decode_data(result))

def main():  app = app = QtGui.QApplication(sys.argv)
   qb = MyDict()
   qb.show()
   sys.exit(app.exec_())

def get_translate(word):  url = 'http://fanyi.youdao.com/openapi.do'  data = {  'keyfrom': KEYFROM,
   'key': API_KEY,
   'type': 'data',
   'doctype': 'json',
   'version': 1.1,
   'q': word
   }  data = urllib.urlencode(data)
   url = url+'?'+data
   req = urllib2.Request(url)
   response = urllib2.urlopen(req)
   result = json.loads(response.read())
   return result

def decode_data(json_data):  query = json_data.get('query','')
   translation = json_data.get('translation','')
   basic = json_data.get('basic','')
   sequence = json_data.get('web',[])
   phonetic,explains_txt,seq_txt,log_word_explains = '','','',''    if basic:  phonetic = basic.get('phonetic','')
      explains = basic.get('explains',[])
      for obj in explains:  explains_txt += obj+'\n'  log_word_explains += obj+','   if sequence:  for obj in sequence:  seq_txt += obj['key']+'\n'  values = ''  for i in obj['value']:  values += i+','  seq_txt += values+'\n'   print_format = '*'*40 + '\n'  print_format += u'查询的单词: %s [%s]\n' %(query, phonetic)
   print_format += explains_txt
   print_format += '-'*20+'\n'+seq_txt
   print_format += '*'*40+'\n'  #gbk_format = print_format.encode('GBK', 'ignore')
   #print gbk_format
   return print_format


if __name__ == "__main__":  main()

下面是效果;









你可能感兴趣的:(json,python,GUI,有道翻译)