linux终端下实现有道翻译

参考链接1
参考链接2

  1. 有道翻译的代码如下
    先将此代码复制到一个文件里面,并将这个文件放到~/Documents下,命名为youdao.py

版本一

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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#! /usr/bin/python
import re;
import urllib;
import urllib2;
import sys;
def debug():
xml = open("word.xml").read();
print get_text(xml);
print get_elements_by_path(xml, "custom-translation/content");
#print_translations(xml, False, False);
def get_elements_by_path(xml, elem):
if type(xml) == type(''):
xml = [xml];
if type(elem) == type(''):
elem = elem.split('/');
if (len(xml) == 0):
return [];
elif (len(elem) == 0):
return xml;
elif (len(elem) == 1):
result = [];
for item in xml:
result += get_elements(item, elem[0]);
return result;
else:
subitems = [];
for item in xml:
subitems += get_elements(item, elem[0]);
return get_elements_by_path(subitems, elem[1:]);
textre = re.compile("\!\[CDATA\[(.*?)\]\]", re.DOTALL);
def get_text(xml):
match = re.search(textre, xml);
if not match:
return xml;
return match.group(1);
def get_elements(xml, elem):
p = re.compile("<" + elem + ">" + "(.*?)</" + elem + ">", re.DOTALL);
it = p.finditer(xml);
result = [];
for m in it:
result.append(m.group(1));
return result;
GREEN = "\033[1;32m";
DEFAULT = "\033[0;49m";
BOLD = "\033[1m";
UNDERLINE = "\033[4m";
NORMAL = "\033[m";
RED = "\033[1;31m"
def crawl_xml(queryword):
return urllib2.urlopen("http://dict.yodao.com/search?keyfrom=dict.python&q="
+ urllib.quote_plus(queryword) + "&xmlDetail=true&doctype=xml").read();
def print_translations(xml, with_color, detailed):
#print xml;
original_query = get_elements(xml, "original-query");
queryword = get_text(original_query[0]);
custom_translations = get_elements(xml, "custom-translation");
print BOLD + UNDERLINE + queryword + NORMAL;
translated = False;

for cus in custom_translations:
source = get_elements_by_path(cus, "source/name");

print RED + "Translations from " + source[0] + DEFAULT;
contents = get_elements_by_path(cus, "translation/content");
if with_color:
for content in contents[0:5]:
print GREEN + get_text(content) + DEFAULT;
else:
for content in contents[0:5]:
print get_text(content);
translated = True;

yodao_translations = get_elements(xml, "yodao-web-dict");
printed = False;
for trans in yodao_translations:
webtrans = get_elements(trans, "web-translation");
for web in webtrans[0:5]:
if not printed:
print RED + "Translations from yodao:" + DEFAULT;
printed = True;
keys = get_elements(web, "key");
values = get_elements_by_path(web, "trans/value");
summaries = get_elements_by_path(web, "trans/summary");
key = keys[0].strip();
value = values[0].strip();
#summary = summaries[0].strip();
#lines = get_elements(summary, "line");
if with_color:
print BOLD + get_text(key) + ":\t" +DEFAULT + GREEN + get_text(value) + NORMAL;
#for line in lines:
# print GREEN + get_text(line) + DEFAULT;
#print get_text(summary) + DEFAULT;
else:
print get_text(value);
#print get_text(summary);
#translated = True;
#if not detailed:
# break

def usage():
print "usage: dict.py word_to_translate";
def main(argv):
if len(argv) <= 0:
usage();
#debug();
sys.exit(1);
xml = crawl_xml(" ".join(argv));
print_translations(xml, True, False);

if __name__ == "__main__":
main(sys.argv[1:]);

版本二(simply)

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
#!/usr/bin/env python
# -*- coding:utf-8 -*-

# API key:273646050
# keyfrom:11pegasus11

import json
import sys

try: # py3
from urllib.parse import urlparse, quote, urlencode, unquote
from urllib.request import urlopen
except: # py2
from urllib import urlencode, quote, unquote
from urllib2 import urlopen


def fetch(query_str=''):
query_str = query_str.strip("'").strip('"').strip()
if not query_str:
query_str = 'python'

print(query_str)
query = {
'q': query_str
}
url = 'http://fanyi.youdao.com/openapi.do?keyfrom=11pegasus11&key=273646050&type=data&doctype=json&version=1.1&' + urlencode(query)
response = urlopen(url, timeout=3)
html = response.read().decode('utf-8')
return html


def parse(html):
d = json.loads(html)
try:
if d.get('errorCode') == 0:
explains = d.get('basic').get('explains')
for i in explains:
print(i)
else:
print('无法翻译')

except:
print('翻译出错,请输入合法单词')


def main():
try:
s = sys.argv[1]
except IndexError:
s = 'python'
parse(fetch(s))


if __name__ == '__main__':
main()

  1. 创建一个脚本,放在~/下,命名为fy

    1
    2
    3
    4
    5
    6
    #! /bin/bash
    while [ $# -ne 0 ]
    do
    python ~/Documents/youdao.py $1
    shift
    done
  2. 赋予脚本可执行的权限
    chmod u+x fy

  3. 将该脚本链接到/usr/bin下
    sudo ln -s ~/fy /usr/bin/fy

  4. 输入fy 单词/汉语 就可以翻译了Oh yeah!

注:这里其实还有一种很神奇的办法,在Linux之中有一种叫做命令别名的东西,即alias 别名=’命令参数’
比如说这里使用chmod u+x youdao.py,讲youdao.py变为可执行文件之后,可以使用命令./youdao.py来执行,那么我该怎么做呢,首先vim .bashrc,打开.bashrc文件,将alias fy=’/home/username/./youdao.py’添加到文件的末尾,然后使用source .bashrc来使其生效即可,/home/username/是你的目录名,fy=’/home/username/./youdao.py’的意思是将/home/username/./youdao.py起一个别名,为fy,这样你虽然命令为fy,但其实是后面的那一长串命令的效果

文章目录
|