Merge pull request #43 from patzzz/master

Get definitions, examples, pronunciations, phonetic symbols and derivatives from Oxford API
This commit is contained in:
sthoo 2018-08-24 20:09:32 +08:00 committed by GitHub
commit ea09a11c3d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 152 additions and 31 deletions

View File

@ -1,30 +1,90 @@
#-*- coding:utf-8 -*-
import os
import urllib2
import json
from ..base import *
oxford_download_mp3 = True
@register(u"Oxford")
@register(u'Oxford')
class Oxford(WebService):
def __init__(self):
super(Oxford, self).__init__()
def _get_from_api(self, lang="en"):
word = self.word
baseurl = "https://od-api.oxforddictionaries.com/api/v1"
app_id = "45aecf84"
app_key = "bb36fd6a1259e5baf8df6110a2f7fc8f"
headers = {"app_id": app_id, "app_key": app_key}
def _get_from_api(self, lang='en'):
app_id = '45aecf84'
app_key = 'bb36fd6a1259e5baf8df6110a2f7fc8f'
headers = {'app_id': app_id, 'app_key': app_key}
word_id = urllib2.quote(self.word.lower().replace(' ', '_'))
url = u'https://od-api.oxforddictionaries.com/api/v1/entries/' + lang + u'/' + word_id
result = {'lexicalEntries': ''}
try:
result.update(json.loads(self.get_response(url, headers=headers, timeout=10))['results'][0])
except:
pass
return self.cache_this(result)
word_id = urllib2.quote(word.lower().replace(" ", "_"))
url = baseurl + "/entries/" + lang + "/" + word_id
url = urllib2.Request(url, headers=headers)
response = json.loads(urllib2.urlopen(url).read())
@export('DEF')
def fld_definition(self):
try:
return self._get_field('lexicalEntries')[0]['entries'][0]['senses'][0]['definitions'][0]
except:
return ''
return response["results"]
def _fld_pron_mp3(self, audio_url):
if oxford_download_mp3 and audio_url:
filename = get_hex_name(self.unique.lower(), audio_url, 'mp3')
if os.path.exists(filename) or self.net_download(filename, audio_url):
return self.get_anki_label(filename, 'audio')
return ''
@export("Lexical Category")
def fld_category(self):
return self._get_from_api()[0]["lexicalEntries"][0]["lexicalCategory"]
@export('PRON')
def fld_pron(self):
try:
entries = self._get_field('lexicalEntries')
prons_mp3 = ''
for entry in entries:
if 'pronunciations' in entry:
prons = entry['pronunciations']
pos = entry['lexicalCategory']
prons_mp3 += '<br>' if prons_mp3 else '' + u'<br>'.join(
u'{0}({1}) {2}'.format(
pron['dialects'][0] + ' ' if 'dialects' in pron else '',
pos,
self._fld_pron_mp3(pron['audioFile'])) for pron in prons)
return prons_mp3
except:
return ''
@export('PHON')
def fld_phon(self):
try:
prons = self._get_field('lexicalEntries')[0]['pronunciations']
return u'<br>'.join(u'{0}{1}'.format(pron['dialects'][0] + ': ' if 'dialects' in pron else '', pron['phoneticSpelling']) for pron in prons)
except:
return ''
@export('EXAMPLE')
def fld_example(self):
try:
entries = self._get_field('lexicalEntries')[0]['entries'][0]['senses'][0]['examples']
return u'<br>'.join(entry['text'] for entry in entries)
except:
return ''
@export(u'Derivatives')
def fld_deriv(self):
try:
entries = self._get_field('lexicalEntries')[0]['derivatives']
return u', '.join(entry['text'] for entry in entries)
except:
return ''
@export([u'词性', u'POS'])
def fld_pos(self):
try:
entries = self._get_field('lexicalEntries')
return u', '.join(entry['lexicalCategory'] for entry in entries)
except:
return ''

View File

@ -1,4 +1,5 @@
#-*- coding:utf-8 -*-
import os
try:
import urllib2
except:
@ -7,27 +8,87 @@ import json
from aqt.utils import showInfo
from ..base import WebService, export, register, with_styles
oxford_download_mp3 = True
@register(u"Oxford")
@register(u'Oxford')
class Oxford(WebService):
def __init__(self):
super(Oxford, self).__init__()
def _get_from_api(self, lang="en"):
word = self.word
baseurl = "https://od-api.oxforddictionaries.com/api/v1"
app_id = "45aecf84"
app_key = "bb36fd6a1259e5baf8df6110a2f7fc8f"
headers = {"app_id": app_id, "app_key": app_key}
def _get_from_api(self, lang='en'):
app_id = '45aecf84'
app_key = 'bb36fd6a1259e5baf8df6110a2f7fc8f'
headers = {'app_id': app_id, 'app_key': app_key}
word_id = urllib2.quote(self.word.lower().replace(' ', '_'))
url = u'https://od-api.oxforddictionaries.com/api/v1/entries/' + lang + u'/' + word_id
result = {'lexicalEntries': ''}
try:
result.update(json.loads(self.get_response(url, headers=headers, timeout=10))['results'][0])
except:
pass
return self.cache_this(result)
word_id = urllib2.quote(word.lower().replace(" ", "_"))
url = baseurl + "/entries/" + lang + "/" + word_id
url = urllib2.Request(url, headers=headers)
response = json.loads(urllib2.urlopen(url).read())
@export('DEF')
def fld_definition(self):
try:
return self._get_field('lexicalEntries')[0]['entries'][0]['senses'][0]['definitions'][0]
except:
return ''
return response["results"]
def _fld_pron_mp3(self, audio_url):
if oxford_download_mp3 and audio_url:
filename = get_hex_name(self.unique.lower(), audio_url, 'mp3')
if os.path.exists(filename) or self.net_download(filename, audio_url):
return self.get_anki_label(filename, 'audio')
return ''
@export("Lexical Category")
def _fld_category(self):
return self._get_from_api()[0]["lexicalEntries"][0]["lexicalCategory"]
@export('PRON')
def fld_pron(self):
try:
entries = self._get_field('lexicalEntries')
prons_mp3 = ''
for entry in entries:
if 'pronunciations' in entry:
prons = entry['pronunciations']
pos = entry['lexicalCategory']
prons_mp3 += '<br>' if prons_mp3 else '' + u'<br>'.join(
u'{0}({1}) {2}'.format(
pron['dialects'][0] + ' ' if 'dialects' in pron else '',
pos,
self._fld_pron_mp3(pron['audioFile'])) for pron in prons)
return prons_mp3
except:
return ''
@export('PHON')
def fld_phon(self):
try:
prons = self._get_field('lexicalEntries')[0]['pronunciations']
return u'<br>'.join(u'{0}{1}'.format(pron['dialects'][0] + ': ' if 'dialects' in pron else '', pron['phoneticSpelling']) for pron in prons)
except:
return ''
@export('EXAMPLE')
def fld_example(self):
try:
entries = self._get_field('lexicalEntries')[0]['entries'][0]['senses'][0]['examples']
return u'<br>'.join(entry['text'] for entry in entries)
except:
return ''
@export(u'Derivatives')
def fld_deriv(self):
try:
entries = self._get_field('lexicalEntries')[0]['derivatives']
return u', '.join(entry['text'] for entry in entries)
except:
return ''
@export([u'词性', u'POS'])
def fld_pos(self):
try:
entries = self._get_field('lexicalEntries')
return u', '.join(entry['lexicalCategory'] for entry in entries)
except:
return ''