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()

下面是效果;









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值