python网页抓取之自己动手写字典

  由于上篇的是在命令行中获取翻译的,方便性肯定一般啦。最多算个

好玩些罢了。周末没事,就把上篇的代码搬进基于pyqt4中的图形软件中了。

   上篇代码当作模块使用不方便,做了更改,另外,两点注意:

1.qt支持html的标签对于字符串的修饰。

比如:<font color="red">string</font> 显示的是红色的string。

2.存储在数据库中存储翻译时使用的' '换行符如果使用标签修饰就会失效,

只能在存储时换成<br>来分割不同的翻译,当然如果你不用这种方法显示

字符串就不需要考虑<br>了,下图字符串是用标签修饰后的效果。

 本人自己的电脑装的是linux mint,默认窗体就是这个样子,透明度是0.9。

OK按钮翻译输入框的单词(快捷键回车),clip按钮翻译剪切板的单词(快捷键

是shift),如果不是单词,程序会过滤掉。

  鼠标离开主窗体(快捷键alt可以直接隐藏主窗体)仅显示:

  

双击它唤出主窗体(快捷键:x)。

实现的窗体代码如下,获取翻译模块部分可以去:

https://github.com/915546302/dictionary

  1 #!/usr/bin/python
  2 #--*--coding:utf-8--*--
  3 
  4 import sys,re
  5 from PyQt4 import QtGui
  6 from PyQt4 import QtCore
  7 from dic import Fecth
  8 import time
  9 class IrregularForm(QtGui.QWidget): 
 10         def __init__(self, parent=None):
 11             QtGui.QWidget.__init__(self, parent)
 12             self.parent=parent
 13 
 14             mask=QtGui.QPixmap("./icons/search40.png")
 15             self.setMask(QtGui.QBitmap(mask.mask()))
 16             p=QtGui.QPalette()
 17             p.setBrush(QtGui.QPalette.Window, QtGui.QBrush(mask))
 18             self.setPalette(p)
 19             self.setGeometry(100, 100, 100, 100)
 20             self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
 21             self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
 22             self.setWindowIcon(QtGui.QIcon('./icons/search50.png'))
 23             self.mouseMovePos = QtCore.QPoint(0, 0)
 24         def mouseMoveEvent(self,event):
 25              if(self.mouseMovePos != QtCore.QPoint(0, 0)):
 26                 self.move(self.geometry().x() + event.globalPos().x() 
 27                     - self.mouseMovePos.x(),self.geometry().y() 
 28                     + event.globalPos().y() - self.mouseMovePos.y())
 29                 self.mouseMovePos = event.globalPos()
 30         def mousePressEvent(self,event):
 31             self.mouseMovePos = event.globalPos()
 32 
 33         def mouseReleaseEvent(self,event):
 34             self.mouseMovePos = QtCore.QPoint(0, 0)
 35         def mouseDoubleClickEvent(self, event):
 36             self.emit(QtCore.SIGNAL('trueVisible()'))
 37         def keyPressEvent(self, event):
 38             if event.key() == QtCore.Qt.Key_X:
 39                 self.emit(QtCore.SIGNAL('trueVisible()'))
 40 class Dic(QtGui.QWidget):
 41     def __init__(self, parent=None):
 42         QtGui.QWidget.__init__(self, parent)
 43         self.alt=None
 44         self.irregular=IrregularForm()
 45         self.irregular.show() 
 46  
 47         self.curTime=time.strftime("%Y-%m-%d %H:%M", 
 48             time.localtime(time.time()))
 49         okButton = QtGui.QPushButton("OK")
 50         cbbtn = QtGui.QPushButton("clip")
 51 
 52         self.edit = QtGui.QLineEdit()
 53         self.word = QtGui.QLabel( self.curTime)
 54         rem = QtGui.QLabel('<h2><i>Word:</i></h2>')
 55         self.edit.setStyleSheet("color: blue;" 
 56                          "selection-color: yellow;" 
 57                          "selection-background-color: blue;")
 58         #cbbtn.setStyleSheet("color:red");
 59         cbbtn.setStyleSheet("color: blue;border:2px groove gray;"
 60                           "border-radius:10px;padding:2px 4px;")
 61         okButton.setStyleSheet("border:2px groove gray;"
 62                           "border-radius:10px;padding:2px 4px;")
 63 
 64         hbox = QtGui.QHBoxLayout()
 65         hbox.addWidget(rem)
 66         hbox.addWidget(self.edit)
 67         hbox.addWidget(okButton)
 68         hbox.addWidget(cbbtn)
 69 
 70         vbox = QtGui.QVBoxLayout()
 71         vbox.addLayout(hbox)
 72         vbox.addWidget(self.word)
 73         
 74         self.setLayout(vbox)
 75         self.setWindowOpacity(0.95)
 76         self.setWindowTitle('Dictionary')
 77         self.setGeometry(300, 300, 350, 150)
 78         self.setWindowIcon(QtGui.QIcon('./icons/search50.png'))
 79         self.connect(okButton, QtCore.SIGNAL('clicked()'), 
 80             self.okButton)
 81         self.connect(cbbtn, QtCore.SIGNAL('clicked()'), 
 82             self.clipboardBotton)
 83         self.connect(self.irregular, QtCore.SIGNAL('trueVisible()'), 
 84             self,QtCore.SLOT('trueVisible()') )
 85         #self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
 86         self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
 87         #self.fe=Fecth()
 88     @QtCore.pyqtSlot()
 89     def trueVisible(self):
 90         self.setVisible(True)
 91         self.irregular.setVisible(False)
 92 
 93     def clipboardBotton(self):
 94         clipboard = QtGui.QApplication.clipboard()
 95         print clipboard.text()
 96         self.edit.setText(clipboard.text())
 97         self.buttonClicked(clipboard.text())
 98     def okButton(self):
 99         src=self.edit.text()
100         self.buttonClicked(src)
101     def setColor(self,string,key):
102         if key=='red':
103             return '<font color="red">'+string+'</font>'+'<br>'
104         elif key=='blue':
105             return '<font color="blue">'+string+'</font>'+'<br>'
106         else:
107             return '<font color="green">'+string+'</font>'+'<br>'
108     def buttonClicked(self,src):
109 
110         g=re.match('[a-zA-Z]+',src)
111         if not g:
112             self.word.setText(self.setColor('<h3>Not a word!</h3>','red'))
113             return
114         src=g.group()
115         self.fe=Fecth()
116         rows=self.fe.searchDB(src,None)
117         trans=''
118         if rows:
119             for row in rows:
120                 trans = self.setColor(row[0],'red')
121                 if row[1]!='':
122                    trans+=self.setColor(row[1]+','+row[2],'blue')
123                 trans+= self.setColor(row[3],'green')
124             self.word.setText('<h3>'+trans+'</h3>')
125         else:
126             
127             trans=self.setColor(src,'red')
128             zh=self.fe.fecth('qt')
129             print zh[0],zh[1]
130             trans+=self.setColor(zh[0],'blue')
131             tmp=zh[1]
132             if tmp=='':
133                 tmp='<b>Fetch fail!</b>'
134             trans+= self.setColor(tmp,'green')
135             self.word.setText('<h3>'+trans+'</h3>')
136         self.fe.close()
137     def keyReleaseEvent(self, event):
138             
139             if event.key() == QtCore.Qt.Key_Return:
140                 self.okButton()
141             elif event.key() == QtCore.Qt.Key_Shift:
142                 self.clipboardBotton()
143             elif event.key() == QtCore.Qt.Key_Alt:
144                 self.alt=QtCore.Qt.Key_Alt
145                 self.setVisible(False)
146                 self.irregular.setVisible(True)
147             elif event.key() == QtCore.Qt.Key_Space:
148                 self.edit.setText('')
149     def closeEvent(self, event):
150         
151         QtGui.qApp.quit()
152         #self.irregular.destroy()
153     def leaveEvent(self,evt): 
154         if self.alt==QtCore.Qt.Key_Alt:
155             self.alt=-1
156             return
157         cx,cy=QtGui.QCursor.pos().x(),QtGui.QCursor.pos().y()
158         if(cx >= self.x() and cx <= self.x()+self.width()
159             and cy >= self.y() and cy <=self.y()+self.height()):
160             pass
161         else:
162             
163             self.irregular.setVisible(True)
164             self.setVisible(False)
165             #self.setWindowOpacity(0.3)
166 
167 app = QtGui.QApplication(sys.argv)
168 dic = Dic()
169 dic.show()
170 sys.exit(app.exec_())
View Code

  更详细的内容可以去github上了解,代码很多需要优化,很多本人不满意的地方,

应该重新架构一下。

  可以根据自己的喜好设置窗体的显示和热键啦,代码作为例子分享下,

随便修改,如果能共同开发出在linux下不错的翻译软件那就更好了,^_^。

原文地址:https://www.cnblogs.com/wuchaofan/p/3405047.html