#-*- coding:utf-8 -*- import urllib import urllib2 import re from collections import defaultdict from .base import export, with_styles from .webservice import WebService from aqt.utils import showInfo css = ''' ''' js = ''' var initVoice = function () { var player = document.getElementById('dictVoice'); document.addEventListener('click', function (e) { var target = e.target; if (target.hasAttribute('role') && target.getAttribute('role').indexOf('dict_audio_js') >= 0) { var url = target.getAttribute('data-rel'); player.setAttribute('src', url); player.volume = 1; player.play(); e.preventDefault(); } }, false); }; initVoice(); ''' class Vocabulary(WebService): __register_label__ = u'vocabulary.com' def __init__(self): super(Vocabulary, self).__init__() self.cache = defaultdict(defaultdict) def _get_content(self): url = "https://www.vocabulary.com/dictionary/definition.ajax?search=%s" % self.word try: result = urllib2.urlopen(url, timeout=5).read() self.cache[self.word] = {'short': '', 'long': '', 'primary': '', 'full': ''} m = re.search('(

.*?

)', result) if m: self.cache[self.word]['short'] = m.groups()[0] m = re.search('(

.*?

)', result) if m: self.cache[self.word]['long'] = m.groups()[0] m = re.search( '()', result, re.DOTALL) if m: self.cache[self.word][ 'primary'] = '
' + m.groups()[0] + '
' m = re.findall( '(
.*?
)', result, re.DOTALL) if m: self.cache[self.word][ 'full'] = '
' + ''.join(m) + '
' except Exception as e: showInfo(str(e)) pass @export(u'Short Description', 2) def fld_short_desc(self): if self.word not in self.cache or not self.cache[self.word].has_key('short'): self._get_content() return self.cache[self.word]['short'] @export(u'Long Description', 3) def fld_long_desc(self): if self.word not in self.cache or not self.cache[self.word].has_key('long'): self._get_content() return self.cache[self.word]['long'] @export(u'Primary Meanings', 4) @with_styles(css=css) def fld_primary_meanings(self): if self.word not in self.cache or not self.cache[self.word].has_key('primary'): self._get_content() return self.cache[self.word]['primary'] @with_styles(css=css) @export(u'Full Definitions', 5) def fld_full_definitions(self): if self.word not in self.cache or not self.cache[self.word].has_key('full'): self._get_content() return self.cache[self.word]['full']