-
Notifications
You must be signed in to change notification settings - Fork 2
/
dict
executable file
·70 lines (63 loc) · 2.22 KB
/
dict
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
65
66
67
68
69
#!/usr/bin/env python3
import sys
from os.path import expanduser
import json
import requests
def make_request(text, keys):
text = text.strip()
if text == '':
return
url = ('http://fanyi.youdao.com/openapi.do?' +\
'keyfrom={}&key={}&' +\
'type=data&doctype=json&version=1.1&' +\
'q={}').format(keys[0], keys[1], text)
resp = requests.post(url).text
#print('url: ' + url)
#print('response: ' + resp)
jsobj = json.loads(resp)
translations = jsobj['translation'] if 'translation' in jsobj else None
_basic = jsobj['basic'] if 'basic' in jsobj else None
phonetic = _basic['phonetic'] if _basic and 'phonetic' in _basic else None
explains = _basic['explains'] if _basic and 'explains' in _basic else []
print('----------------')
all_translations = set(translations + explains)
for tran in all_translations:
print(' {}'.format(tran))
if phonetic:
print(' |{}|'.format(phonetic))
_webs = jsobj['web'] if 'web' in jsobj else None
if _webs:
padding_space = ' ' if is_eng_text(text) else ' '
print('e.g.')
max_length = max(len(_web['key']) for _web in _webs)
for _web in _webs:
key = _web['key']
values = _web['value']
print(' {0:{1}<{2}} : {3}'.format(key, padding_space, max_length, '; '.join(values)))
print('--------------------------------')
def is_eng_text(text):
eng_letters = 0
for ch in text.lower():
if ch >= 'a' and ch <= 'z':
eng_letters += 1
return eng_letters > 0.8 * len(text)
def get_config():
with open(expanduser('~/.dict_config'), 'r') as file_handler:
data = file_handler.read().split('\n')
return data
def is_bye_word(text):
return text == 'bye' or text == 'exit'
def main():
if len(sys.argv) == 1:
# enter shell mode
print('--------------------------------')
text = input('Look up: ')
while not is_bye_word(text):
make_request(text, get_config())
print()
print('--------------------------------')
text = input('Look up: ')
else:
text = sys.argv[1]
make_request(text, get_config())
main()