Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# 'summary': {
# 'word': ...,
# 'pronounce': [('KK', '...'), (...)], // optional.
# // e.g. 'google'
# 'explain': [(optional)], # 'hospitalized' is summary-only
# 'grammar': [(optional)],
# },
# 'explain': [...],
# 'verbose': [(optional)],
# }
# Construct summary (required)
try:
content['summary'] = self.parse_summary(data, word)
except AttributeError:
raise NotFoundError(word)
# Handle explain (required)
try:
content['explain'] = self.parse_explain(data)
except IndexError:
raise NotFoundError(word)
# Extract verbose (optional)
content['verbose'] = self.parse_verbose(data)
record = Record(
word=word,
content=json.dumps(content),
source=self.provider,
)
return record
import peewee
from zdict.constants import DB_FILE
db = peewee.SqliteDatabase(DB_FILE)
class Record(peewee.Model):
'''
A model for storing the query results into the SQLite db.
:param word: the vocabulary
:param content: the query result of the vocabulary.
It's a json document has the following spec.
{
'word': word,
// storing the querying result.
'pronounce': [
('key', 'value'),
...
],
lambda x: re.match(r'(.*)(\[.*\])', x).groups(),
p.find('ul').text.strip().split()
)
)
def get_grammar(d: bs4.element.Tag):
s = ('div#web ol.searchCenterMiddle '
'div.dictionaryWordCard > ul > li')
return list(map(text, d.select(s)))
node = data.select_one('div#web ol.searchCenterMiddle')
node = node.select('div.sys_dict_word_card > div.grp-main > div')
p = None # optional
if node is None or len(node) <= 1: # e.g. "fabor"
raise NotFoundError(word)
elif len(node) == 2: # e.g. "apples"
w, e = node
elif len(node) == 3: # e.g. ?
w, _, e = node
elif len(node) == 4: # e.g. ?
w, _, _, e = node
elif len(node) == 5: # e.g. "metadata"
w, p, _, _, e = node
elif len(node) == 6:
w, p, _, _, _, e = node
return {
'word': w.find('span').text.strip(),
'pronounce': get_pronounce(p) if p else [], # optional
'explain': get_explain(e),
'grammar': get_grammar(data), # optional
if record:
self.show(record)
return
try:
record = self.query(word)
except exceptions.NoNetworkError as e:
self.color.print(e, 'red')
print()
except exceptions.TimeoutError as e:
self.color.print(e, 'red')
print()
except exceptions.APIKeyError as e:
self.color.print(e, 'red')
print()
except exceptions.NotFoundError as e:
self.color.print(e, 'yellow')
print()
except Exception:
import traceback
traceback.print_exc()
url = "https://github.com/zdict/zdict/issues"
print()
print("We have problem for this word 😢")
print("Please report this word to {}".format(url))
print("Dictionary: {}".format(self.title))
print("Word: '{}'".format(word))
import sys
sys.exit(1)
else:
self.save(record, word)
self.show(record)
def set_args(args):
if args.force_color:
utils.Color.set_force_color()
args.dict = args.dict.split(',')
if 'all' in args.dict:
args.dict = tuple(dictionary_map.keys())
else:
# Uniq and Filter the dict not in supported dictionary list then sort.
args.dict = sorted(set(d for d in args.dict if d in dictionary_map))
if len(args.dict) > 1:
args.show_provider = True
return args
def set_args():
if args.list_dicts:
for provider in sorted(dictionary_map, key=lambda x: x if x != 'yahoo' else ''):
print('{}: {}'.format(provider, dictionary_map[provider]().title))
exit()
utils.Color.colorize = args.force_color
args.dict = args.dict.split(',')
if 'all' in args.dict:
args.dict = tuple(dictionary_map.keys())
else:
# Uniq and Filter the dict not in supported dictionary list then sort.
args.dict = sorted(set(d for d in args.dict if d in dictionary_map))
if len(args.dict) > 1:
args.show_provider = True
def show_pyjoke(record: Record):
if not record:
return
for i, s in enumerate(
re.split(r'\b({})\b'.format(record.word), record.content)
):
Color.print(
s,
'lindigo' if i % 2 else 'indigo',
end=''
)
print('\n\n', end='')
app_id,app_key
.. note:: request limit
request limit: per minute is 60, per month is 3000.
"""
if not os.path.exists(self.KEY_FILE):
self.color.print('You can get an API key by the following steps:',
'yellow')
print('1. Register a developer account at '
'https://developer.oxforddictionaries.com/')
print('2. Get the application id & keys in the `credentials` page')
print('3. Paste the API key at `{key_file}` in the foramt:'.format(
key_file=self.KEY_FILE
))
print(' app_id, app_key')
raise APIKeyError('Oxford: API key not found')
with open(self.KEY_FILE) as fp:
keys = fp.read()
keys = re.sub(r'\s', '', keys).split(',')
if len(keys) != 2:
print('The API key should be placed in the format:')
print(' app_id, app_key')
raise APIKeyError('Oxford: API key file format not correct.')
return keys
'https://developer.oxforddictionaries.com/')
print('2. Get the application id & keys in the `credentials` page')
print('3. Paste the API key at `{key_file}` in the foramt:'.format(
key_file=self.KEY_FILE
))
print(' app_id, app_key')
raise APIKeyError('Oxford: API key not found')
with open(self.KEY_FILE) as fp:
keys = fp.read()
keys = re.sub(r'\s', '', keys).split(',')
if len(keys) != 2:
print('The API key should be placed in the format:')
print(' app_id, app_key')
raise APIKeyError('Oxford: API key file format not correct.')
return keys
if not self.args.disable_db_cache:
record = self.query_db_cache(word)
if record:
self.show(record)
return
try:
record = self.query(word)
except exceptions.NoNetworkError as e:
self.color.print(e, 'red')
print()
except exceptions.TimeoutError as e:
self.color.print(e, 'red')
print()
except exceptions.APIKeyError as e:
self.color.print(e, 'red')
print()
except exceptions.NotFoundError as e:
self.color.print(e, 'yellow')
print()
except Exception:
import traceback
traceback.print_exc()
url = "https://github.com/zdict/zdict/issues"
print()
print("We have problem for this word 😢")
print("Please report this word to {}".format(url))
print("Dictionary: {}".format(self.title))
print("Word: '{}'".format(word))
import sys
sys.exit(1)