-
Notifications
You must be signed in to change notification settings - Fork 1
/
American Says.py
64 lines (53 loc) · 2.14 KB
/
American Says.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# -*- coding:utf-8 -*-
# import the main window object (mw) from ankiqt
from aqt import mw
# import the "show info" tool from utils.py
from aqt.utils import showInfo
# import all of the Qt GUI library
from aqt.qt import *
from anki.hooks import addHook
import urllib2
from HTMLParser import HTMLParser
from PyQt4.QtGui import QApplication
class MyHTMLParser(HTMLParser):
result = []
def handle_starttag(self, tag, attrs):
if tag == 'a':
for attr in attrs:
if 'data-file' in attr[0]:
self.result.append(attr[1])
class AmericanSays:
BASE_URL = 'http://www.merriam-webster.com/dictionary/'
MP3_URL = 'http://media.merriam-webster.com/audio/prons/en/us/mp3/%s/%s.mp3'
def get_selected(self, view):
"""Copy selected text. only the first word will be chosen"""
return view.page().selectedText().encode('utf8', 'ignore').split()[0]
def lookup_character_action(self, view):
"""Lookup single character action"""
selected = self.get_selected(view)
content = urllib2.urlopen(
self.BASE_URL + selected).read()
parser = MyHTMLParser()
parser.feed(content)
filename = None
for i in parser.result:
# may have multiple prounce files, but only choose first matched
if i[:6] == selected[:6]:
filename = i
break
# copy link to clipboard
if filename:
clipboard = QApplication.clipboard()
clipboard.clear(mode=clipboard.Clipboard)
clipboard.setText(self.MP3_URL % (filename[0], filename),
mode=clipboard.Clipboard)
else:
showInfo('No prounce file founded.')
def insert_search_menu_action(self, anki_web_view, m):
selected = self.get_selected(anki_web_view)
a = m.addAction('American Says')
a.connect(a, SIGNAL("triggered()"),
lambda wv=anki_web_view: self.lookup_character_action(wv))
# only insert into content menu in editor window
says = AmericanSays()
addHook("EditorWebView.contextMenuEvent", says.insert_search_menu_action)