Skip to content

Instantly share code, notes, and snippets.

@emk emk/Larousse.py

Created Apr 9, 2012
Embed
What would you like to do?
Anki plugin for looking up words in Larousse's native French dictionary
# Based on the ImageDownloader plugin. Quick, dirty and dodgy.
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import urllib
from lxml import etree
from ankiqt.ui.facteditor import FactEditor
from ankiqt.ui.utils import showInfo
def monkeypatch(cls):
"""Add a method to an existing class."""
# Written by Guido van Rossum.
def decorator(func):
setattr(cls, func.__name__, func)
return func
return decorator
def monkeypatch_after(klass):
"""Attach some code at the end of an existing method."""
def decorator(after_method):
original_method = getattr(klass, after_method.__name__)
def wrapper(*args, **kwargs):
result = original_method(*args, **kwargs)
after_method(*args, **kwargs)
return result
setattr(klass, after_method.__name__, wrapper)
return wrapper
return decorator
@monkeypatch_after(FactEditor)
def setupFields(self):
self.larousse = QPushButton(self.widget)
self.larousse.setFixedHeight(20)
#self.larousseSC = QShortcut(QKeySequence(_("F9")), self.widget)
self.larousse.connect(self.larousse, SIGNAL("clicked()"),
self.onLarousse)
#self.larousse.connect(self.larousseSC, SIGNAL("activated()"),
# self.onLarousse)
self.larousse.setToolTip(_("Get definition from Larousse"))
self.larousse.setFixedWidth(80)
self.larousse.setText("Larousse")
self.larousse.setFocusPolicy(Qt.NoFocus)
self.larousse.setEnabled(False)
self.iconsBox.addWidget(self.larousse)
self.larousse.setStyle(self.plastiqueStyle)
@monkeypatch_after(FactEditor)
def enableButtons(self, val=True):
self.larousse.setEnabled(val)
@monkeypatch(FactEditor)
def onLarousse(self):
"""Called when the user asks to look up a word."""
src = self.focusedEdit()
if not src:
return
cursor = src.textCursor()
if not cursor.hasSelection():
return
term = unicode(cursor.selectedText())
note = self.fields['Note']
if not note:
showInfo("Please add a 'Note' field to this card's model")
return
note[1].insertPlainText(fetchDefinition(term))
def fetchDefinition(term):
base = "http://www.larousse.com/fr/dictionnaires/francais/"
url = base + urllib.quote(term.encode('utf-8'))
html = unicode(urllib.urlopen(url).read(), 'utf-8')
root = etree.HTML(html)
defs = root.xpath("//li[@class='DivisionDefinition']//text()")
if defs:
return "\n".join(defs)
else:
showInfo("No definition found.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.