Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

201 lines
6.7KB

  1. #!/usr/bin/python
  2. #-*- coding: utf-8 -*-
  3. #
  4. # KCnrtl is a simple and messy KDE graphical client to access
  5. # the CNRTL linguistic resources
  6. #
  7. # Copyright (C) 2012 Bogdan Cordier
  8. #
  9. # This program is free software: you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation, either version 3 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  21. import sys
  22. import httplib2
  23. from bs4 import BeautifulSoup
  24. from PyQt4.QtCore import *
  25. from PyQt4.QtGui import *
  26. from gui.Ui_kcnrtl import Ui_MainWindow
  27. import re
  28. import shutil
  29. def main():
  30. app = QApplication(sys.argv)
  31. myapp = Main()
  32. myapp.show()
  33. sys.exit(app.exec_())
  34. class Main(QMainWindow):
  35. def __init__(self, parent=None):
  36. super(QWidget, self).__init__(parent)
  37. self.ui = Ui_MainWindow()
  38. self.ui.setupUi(self)
  39. self.ui.lineEdit.selectAll()
  40. self.ui.lineEdit.setFocus()
  41. self.ui.comboBox.setCurrentIndex(0)
  42. self.ui.checkBox.setChecked(False)
  43. self.dictionaries = [u"TLFi",
  44. u"Académie 9e Ed.",
  45. u"Académie 8e Ed.",
  46. u"Académie 4e Ed.",
  47. ]
  48. self.ui.comboBox_2.addItems(self.dictionaries)
  49. self.clipboard = QApplication.clipboard()
  50. self.ui.lineEdit.returnPressed.connect(self.updateUi)
  51. self.ui.comboBox.activated.connect(self.onComboChange)
  52. self.ui.webView.settings().setUserStyleSheetUrl(
  53. QUrl.fromLocalFile(':/lexi.css'))
  54. self.ui.listView.clicked.connect(self.onRowClicked)
  55. self.clipboard.dataChanged.connect(self.autoGetFromClipboard)
  56. def updateUi(self):
  57. try:
  58. # Check if input text is a word
  59. if len(unicode(self.ui.lineEdit.text()).split()) <= 1:
  60. self.typed = unicode(self.ui.lineEdit.text())
  61. self.getLexi(self.typed)
  62. self.ui.comboBox.clear()
  63. self.ui.comboBox.addItems(self.lexiForm())
  64. self.lexiContent()
  65. self.ui.listView.setModel(self.getSynoAnto("synonymie"))
  66. self.ui.listView_2.setModel(self.getSynoAnto("antonymie"))
  67. else:
  68. self.ui.lineEdit.setText("Veuillez entrer UN mot")
  69. except:
  70. self.ui.lineEdit.setText("Veuillez entrer un mot")
  71. # # TODO: Dynamically adjust dictionaries name to windows size
  72. # def resizeEvent(self, event):
  73. # if event.size().width() < 449:
  74. # i = 0
  75. # while i <= len(self.ui.comboBox_2):
  76. # self.ui.comboBox_2.setItemText(i, self.dictionaries_short[i])
  77. # print 'size', event.size().width()
  78. # Copy selected item in list to the clipboard
  79. def onRowClicked(self, qmodelindex):
  80. item = qmodelindex.data(Qt.DisplayRole).toString()
  81. self.clipboard.setText(item)
  82. def autoGetFromClipboard(self):
  83. if self.ui.checkBox.isChecked():
  84. self.ui.lineEdit.setText(unicode(self.clipboard.text()))
  85. self.updateUi()
  86. def onComboChange(self):
  87. self.getLexi(self.typed)
  88. self.lexiContent()
  89. def getSynoAnto(self, form):
  90. tag = []
  91. soup = BeautifulSoup(self.getHtml(self.typed, form))
  92. tagy = soup.find_all('td', "%s_format" % (form[:4]))
  93. i = 0
  94. while i < len(tagy):
  95. tag_a = tagy[i]
  96. tag.append(tag_a.text)
  97. i += 1
  98. model = ListModel(tag, self)
  99. return model
  100. def getLexi(self, text):
  101. h = self.getHtml(text, "definition")
  102. global soup
  103. soup = BeautifulSoup(h, "lxml")
  104. return soup
  105. def lexiContent(self):
  106. tagkeep = soup.find_all('div', {'id': 'contentbox'})
  107. if not self.ui.comboBox_2.currentIndex():
  108. tagrm = soup.find_all('div', {'class': 'tlf_cvedette'})
  109. if 1 <= self.ui.comboBox_2.currentIndex() <= 3:
  110. tagrm = soup.find_all('span', {'class': 'tlf_cvedette'})
  111. tag = str(tagkeep[0]).replace(str(tagrm[0]),'')
  112. self.ui.webView.setHtml(tag.decode('utf8'))
  113. return tag
  114. # Check if there is more than one definition
  115. def lexiForm(self):
  116. a = re.compile("return sendRequest\(5,'/definition/.*")
  117. multdef = soup.find_all('a', {'onclick': a})
  118. tagform = []
  119. i = 0
  120. while i < len(multdef):
  121. multdef_a = multdef[i]
  122. # Delete digits in definition title
  123. multdef_clean = ''.join(c for c in
  124. multdef_a.text if not c.isdigit())
  125. tagform.append(multdef_clean)
  126. i += 1
  127. return tagform
  128. def getHtml(self, text, form):
  129. conn = httplib2.Http('.kcnrtl_cache')
  130. numdef = self.ui.comboBox.currentIndex()
  131. if form == "definition":
  132. if not self.ui.comboBox_2.currentIndex():
  133. htmlSource = conn.request("http://www.cnrtl.fr/%s/%s//%s" %
  134. (form, text, numdef), "GET")
  135. if self.ui.comboBox_2.currentIndex() > 0:
  136. acad = unicode(self.ui.comboBox_2.currentText())
  137. acadnum = filter(lambda x: x.isdigit(), acad)
  138. acadnumf = "academie" + str(acadnum)
  139. htmlSource = conn.request("http://www.cnrtl.fr/%s/%s/%s//%s" %
  140. (form, acadnumf, text, numdef), "GET")
  141. else:
  142. htmlSource = conn.request("http://www.cnrtl.fr/%s/%s" %
  143. (form, text), "GET")
  144. return htmlSource[1]
  145. # Delete cache directory on close
  146. def closeEvent(self, event):
  147. shutil.rmtree('.kcnrtl_cache')
  148. class ListModel(QAbstractListModel):
  149. def __init__(self, datain, parent=None, *args):
  150. """ datain: a list where each item is a row
  151. """
  152. QAbstractListModel.__init__(self, parent, *args)
  153. self.listdata = datain
  154. def rowCount(self, parent=QModelIndex()):
  155. return len(self.listdata)
  156. def data(self, index, role):
  157. if index.isValid() and role == Qt.DisplayRole:
  158. return QVariant(self.listdata[index.row()])
  159. else:
  160. return QVariant()
  161. if __name__ == "__main__":
  162. main()