Skip to content
This repository has been archived by the owner on May 28, 2024. It is now read-only.

Commit

Permalink
6.1.1
Browse files Browse the repository at this point in the history
  • Loading branch information
megachweng committed Nov 13, 2019
2 parents f87de87 + dc8abf9 commit 457d544
Show file tree
Hide file tree
Showing 5 changed files with 200 additions and 3 deletions.
2 changes: 1 addition & 1 deletion addon/constants.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
VERSION = 'v6.1.0'
VERSION = 'v6.1.1'
RELEASE_URL = 'https://github.com/megachweng/Dict2Anki'
VERSION_CHECK_API = 'https://api.github.com/repos/megachweng/Dict2Anki/releases/latest'
MODEL_NAME = f'Dict2Anki-{VERSION}'
Expand Down
4 changes: 2 additions & 2 deletions addon/queryApi/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from . import youdao, bing
from . import youdao, bing, eudict

apis = [youdao.API, bing.API]
apis = [youdao.API, bing.API, eudict.API]
161 changes: 161 additions & 0 deletions addon/queryApi/eudict.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import logging
import requests
from urllib3 import Retry
from requests.adapters import HTTPAdapter
from ..misc import AbstractQueryAPI
from bs4 import BeautifulSoup

logger = logging.getLogger('dict2Anki.queryApi.youdao')
__all__ = ['API']


class Parser:
def __init__(self, html, term):
self._soap = BeautifulSoup(html, 'html.parser')
self.term = term

@property
def definition(self) -> list:
els = self._soap.select('div #ExpFCChild li') # 多词性
els = self._soap.select('div #ExpFCChild .exp') if not els else els # 单一词性
ret = []
for el in els:
ret.append(el.get_text(strip=True))
return ret

@property
def pronunciations(self) -> dict:
url = 'https://api.frdic.com/api/v2/speech/speakweb?'
pron = {
'AmEPhonetic': None,
'AmEUrl': None,
'BrEPhonetic': None,
'BrEUrl': None
}

els = self._soap.select('.phonitic-line')
if els:
el = els[0]
links = el.select('a')
phons = el.select('.Phonitic')

try:
pron['BrEPhonetic'] = phons[0].get_text(strip=True)
except KeyError:
pass

try:
pron['BrEUrl'] = url + links[0]['data-rel']
except (TypeError, KeyError):
pass

try:
pron['AmEPhonetic'] = phons[1].get_text(strip=True)
except KeyError:
pass

try:
pron['AmEUrl'] = url + links[0]['data-rel']
except (TypeError, KeyError):
pass

return pron

@property
def BrEPhonetic(self) -> str:
"""英式音标"""
return self.pronunciations['BrEPhonetic']

@property
def AmEPhonetic(self) -> str:
"""美式音标"""
return self.pronunciations['AmEPhonetic']

@property
def BrEPron(self) -> str:
"""英式发音url"""
return self.pronunciations['BrEUrl']

@property
def AmEPron(self) -> str:
"""美式发音url"""
return self.pronunciations['AmEUrl']

@property
def sentence(self) -> list:
els = self._soap.select('div #ExpLJChild .lj_item')
ret = []
for el in els:
try:
line = el.select('p')
sentence = line[0].get_text(strip=True)
sentence_translation = line[1].get_text(strip=True)
ret.append((sentence, sentence_translation))
except KeyError as e:
pass
return ret

@property
def image(self) -> str:
els = self._soap.select('div .word-thumbnail-container img')
ret = None
if els:
try:
img = els[0]
if 'title' not in img.attrs:
ret = img['src']
except KeyError:
pass
return ret

@property
def phrase(self) -> list:
els = self._soap.select('div #ExpSPECChild #phrase')
ret = []
for el in els:
try:
phrase = el.find('i').get_text(strip=True)
exp = el.find('div').get_text(strip=True)
ret.append((phrase, exp))
except AttributeError:
pass
return ret

@property
def result(self):
return {
'term': self.term,
'definition': self.definition,
'phrase': self.phrase,
'image': self.image,
'sentence': self.sentence,
'BrEPhonetic': self.BrEPhonetic,
'AmEPhonetic': self.AmEPhonetic,
'BrEPron': self.BrEPron,
'AmEPron': self.AmEPron
}


class API(AbstractQueryAPI):
name = '欧陆词典 API'
timeout = 10
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'}
retries = Retry(total=5, backoff_factor=1, status_forcelist=[500, 502, 503, 504])
session = requests.Session()
session.mount('http://', HTTPAdapter(max_retries=retries))
session.mount('https://', HTTPAdapter(max_retries=retries))
url = 'https://dict.eudic.net/dicts/en/{}'
parser = Parser

@classmethod
def query(cls, word) -> dict:
queryResult = None
try:
rsp = cls.session.get(cls.url.format(word), timeout=cls.timeout)
logger.debug(f'code:{rsp.status_code}- word:{word} text:{rsp.text}')
queryResult = cls.parser(rsp.text, word).result
except Exception as e:
logger.exception(e)
finally:
logger.debug(queryResult)
return queryResult
5 changes: 5 additions & 0 deletions anki_addon_page.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
<strong>Dict2Anki</strong> 是一款方便<a href="http://cidian.youdao.com/multi.html" rel="nofollow">有道词典</a>、<a href="https://www.eudic.net/" rel="nofollow">欧陆词典</a>用户同步生成单词本卡片至<a href="https://apps.ankiweb.net/#download" rel="nofollow">Anki</a>的插件

<strong>Change Logs</strong>:
<strong>v6.1.1</strong>:
添加欧陆词典查询API THX to <a href="https://github.com/megachweng/Dict2Anki/pull/73" rel="nofollow">wd</a>
<strong>v6.1.0</strong>:
支持第三方登陆
加入模版字段检查
<strong>v6.0.2</strong>:
添加英英注释 THX to deluser8
<strong>v6.0.1</strong>:
Expand Down
31 changes: 31 additions & 0 deletions test/test_queryapi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from addon.queryApi.eudict import API

api = API()

keys = ('term', 'definition', 'phrase', 'image', 'sentence', 'BrEPhonetic', 'AmEPhonetic', 'BrEPron', 'AmEPron')
def check_result(res):
ret = []
for key in keys:
if not res.get(key):
ret.append(key)
return ret

def test_eudict_no_phrase_and_image():
res = api.query('stint')
ret = check_result(res)
assert set(ret) - set(['image', 'phrase']) == set()

def test_eudict_with_all():
res = api.query('flower')
ret = check_result(res)
assert set(ret) == set()

def test_eudict_with_none():
res = api.query('asafesdf')
ret = check_result(res)
assert set(ret) - set(keys) == set()

def test_eudict_implication_all():
res = api.query('implication')
ret = check_result(res)
assert set(ret) - set(['image']) == set()

0 comments on commit 457d544

Please sign in to comment.