Skip to content

Instantly share code, notes, and snippets.

@ursetto ursetto/
Created Jan 6, 2018

What would you like to do?
Anki add-on providing Forvo and OS X dictionary lookup
# coding: utf-8
Anki add-on providing Forvo and OS X dictionary lookup
of current selection or the 'Expression' field,
via context menu or hotkey.
J Ursetto 2018-01-05
Original source:
Author: Artiom Basenko <>
License: The MIT License (MIT)
Modified to do Forvo lookup and to use 'Expression'
field if text not selected, and to add global menu item and hotkey.
Also added support for OSX dictionary lookup from Eddie Blundell <>
# Stdlib
import urllib
# Anki
from aqt import mw
from aqt.qt import *
from aqt.webview import AnkiWebView
from anki.hooks import addHook
# Qt
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class ZbLookup(object):
OSX_CMD = 'open dict:///%s'
def __init__(self, mw): = mw
def get_selected(self, view):
"""Copy selected text"""
def get_expression(self, view):
exp = mw.reviewer.card.note()['Expression']
return exp
def get_word(self, view):
return self.get_selected(view) or self.get_expression(view)
def lookup_url(self, view, url):
"""Open default browser and look up selected in URL"""
url = QUrl.fromEncoded(url %
self.get_word(view).encode('utf8', 'ignore')))
def lookup_cmd(self, view):
QProcess.startDetached(self.OSX_CMD % self.get_word(view))
def add_action(self, view, menu, action, func):
"""Add action to context menu"""
action = menu.addAction(action)
action.connect(action, SIGNAL('triggered()'), func)
def lookup_forvo_context(self, view, menu):
"""Look up word in context menu"""
word = self.get_word(view)[:10]
self.add_action(view, menu,
u'Forvo 「%s」' % word,
lambda view=view: self.lookup_url(view, self.FORVO_URL))
def lookup_forvo(self):
# menu doesn't pass us a view (AnkiWebView), use mw.web directly
self.lookup_url(mw.web, self.FORVO_URL)
def lookup_osx_dict_context(self, view, menu):
"""Look up word in context menu"""
word = self.get_word(view)[:10]
self.add_action(view, menu,
u'OS X「%s」' % word,
lambda view=view: self.lookup_cmd(view))
def lookup_osx_dict(self):
zbl = ZbLookup(mw)
# Add lookup actions to context menu
addHook("AnkiWebView.contextMenuEvent", zbl.lookup_forvo_context)
addHook("AnkiWebView.contextMenuEvent", zbl.lookup_osx_dict_context)
# Add lookup actions to Tools menu
# menu = mw.form.menuLookup # requires Japanese addon -- FIXME May execute out of order.
menu = QMenu() # create own menu, since can't guarantee order
menu.setTitle("Lookup Zb")
a = QAction(mw)
mw.connect(a, SIGNAL("triggered()"), zbl.lookup_forvo)
a = QAction(mw)
a.setText("OS X dict")
mw.connect(a, SIGNAL("triggered()"), zbl.lookup_osx_dict)
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.