GoldenDict添加自定义词典

GoldenDict添加自定义词典

  本鱼已经忘了3年前的做的一些改动的技术细节了,不过本着能用先扔上来吧,反正俺也不可能重新读一遍代码了。

起因

  某天突然收到有道智云的短信,说余额不足。于是俺登陆了一下,发现确实不足了,充值是不可能充值的,只能换成谷歌翻译白嫖咯。当然为了纪念一下当初改的轮子,还是把代码贴上来咯。(路过的好心人注册一个API分享一下吧)

词典

  首先强烈推荐网友们制作的一些优秀词典,这也是用这个而不是直接用商业软件的初衷,不仅绿色无广告,而且扩展性强。词典可以在掌上百科里面找,嫌这里面要注册麻烦的可以下俺以前收集的:度盘链接,提取码: 7wck。

有道

  因为GoldenDict是词典,但是在平时使用中往往有翻译一句话的需求,因此想把有道翻译或者谷歌翻译加进去。虽然软件本身支持添加URL,但是显示效果什么的挺差,而且有道还有广告,简直不能忍。

  经过俺一番寻找,找到个12年的轮子,但是由于时隔太久,有道API已经改过了,现在需要注册有道智云,这里就不复赘言了,请看官自行注册,然后申请API。

  代码附上,注意需要填写应用ID和密钥:

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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import sys
import json
import http.client
import hashlib
import urllib.request
import random

#api信息
appKey = '你的应用ID'
secretKey = '你的密钥'

html = """
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">function playSound(){var ky = document.getElementById("key");var word = ky.childNodes[0].nodeValue;var api = "http://dict.youdao.com/dictvoice?audio=" + encodeURIComponent(word);var ado = document.getElementById("media");try{ado.ended = true;ado.setAttribute("src",api);ado.load();ado.play();return false;}catch(err){alert(err.description);return false;}}</script>
</head>
<body>
<style type="text/css">
div.block {
border:1px solid #BEBEBE;
background:#F0F0F0;
margin-left:20px;
border-radius: 5px;
}
div.name {
margin-top:10px;
margin-bottom:5px;
margin-left:20px;
font-size:13px;
font-weight:bold;
}
div.item {
padding:5px;
font-size:12px;
margin: 0px 10px 0px 10px;
}
#web {
border-style: none none solid none;
border-color: #BEBEBE;
border-bottom-width: 1px;
}
</style>
<div class="content">
<div class="name"><i>查询:</i></div>
<div class="block">
%s
</div>
<div class="name"><i>有道翻译:</i></div>
<div class="block">
%s
</div>
<div class="name"><i>有道词典-基本词典:</i></div>
<div class="block">
%s
</div>
<div class="name"><i>有道词典-网络释义:</i></div>
<div class="block">
%s
</div>
<div class="name"><i>更多结果:</i></div>
<div class="block">
%s
</div>
</div>
</body>
</html>
"""

errorHtml = """
<html><body>
<div class="block">
<div class="item">%s</div>
</div>
</body></html>
"""

errorResult = {'0':'', '20':'要翻译的文本过长', '30':'无法进行有效的翻译',
'40':'不支持的语言类型', '50':'无效的key'}

def printHtml(errorCode, query, translation, basic, web):
"""打印html"""
if errorCode != "0":
print(errorHtml % errorResult[errorCode])
return
item = '<div class="item">%s</div>'
#有道翻译
q = item % ('<b>"%s"</b>' % query)
trans = ''
for i in translation:
trans += item % ('<b>"%s"</b>' % i)

#有道词典
key = ''
if basic:
key += '<span id="key" style="font-weight:bold">%s</span>' % (query + ' ')
if 'phonetic' in basic.keys():
key += '[%s]' % basic['phonetic']
key += '<button id="sound" onclick="playSound()">sound</button><audio id="media"></audio>'
key = item % key
if 'explains' in basic.keys():
#判断查询的词是不是中文
isChinese = False
for c in query:
if ord(c) >= 0x4e00 and ord(c) <= 0x9fa5:
isChinese = True
break
if not isChinese:
for i in basic['explains']:
key += item % i
else:
for i in basic['explains']:
key += item % ('<a href="%s">%s</a>' % (i, i))
key += item % ('<a href="http://dict.youdao.com/w/%s">%s</a>' % (query, '更多解释'))

#web词典
webdict = ''
webitem = '<div %s class="item">%s<br/>%s</div>'
if web:
if len(web) > 1:
for i in range(len(web)-1):
webdict += webitem % ('id="web"', web[i]['key'], ', '.join(web[i]['value']))
webdict += webitem % ('', web[-1]['key'], ', '.join(web[-1]['value']))

if not key:
key = item % '对不起,没有结果'
if not webdict:
webdict = item % '对不起,没有结果'
#更多搜索
moreSearch = '<div class="item"><a href="https://cn.bing.com/dict/search?q=' + \
query + '">通过Bing词典搜索</a></div>'
moreSearch += '<div class="item"><a href="http://www.iciba.com/' + \
query + '">通过iciba词典搜索</a></div>'
moreSearch += '<div class="item"><a href="http://www.baidu.com/s?wd=' + \
query + '">通过百度搜索</a></div>'
result = html % (q, trans, key, webdict, moreSearch)
utf8stdout = open(1, 'w', encoding='utf-8', closefd=False) # fd 1 is stdout
print(result, file=utf8stdout)

def getData(string):
data = json.loads(string)
errorCode = data['errorCode']
query = data['query']
translation = data['translation']
basic = {}
if 'basic' in data.keys():
basic = data['basic']
web = []
if 'web' in data.keys():
web = data['web']

printHtml(errorCode, query, translation, basic, web)

def searchWord(word):
#加盐
httpClient = None
myurl = '/api'
q = word
fromLang = 'EN'
toLang = 'zh-CHS'
salt = random.randint(1, 65536)
sign = appKey+q+str(salt)+secretKey
m1 = hashlib.md5()
m1.update(sign.encode('UTF-8'))
sign = m1.hexdigest()
myurl = myurl+'?appKey='+appKey+'&q='+urllib.request.quote(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign
try:
httpClient = http.client.HTTPConnection('openapi.youdao.com')
httpClient.request('GET', myurl)

#response是HTTPResponse对象
response = httpClient.getresponse()
k = response.read()
getData(k)
except Exception as e:
print(e)
finally:
if httpClient:
httpClient.close()

if __name__ == '__main__':
searchWord(sys.argv[1])

  将代码保存为Youdao.py。在编辑->词典->程序里添加一个程序,名字填 Youdao,类型选Html,命令填python Youdao.py %GDWORD%

  密钥貌似要经过加盐处理,但是代码是俺18年写的,实在不记得当初怎么解决的了,反正就是这样做没错。如果借用了哪的轮子,只能表示抱歉,俺确实不记得了!

  因为编码问题,原作者代码在Windows下执行有问题,俺貌似稍加改动了一下,具体原理不记得了,反正现在可以跑通!

  最后剩的问题是不能发音,可是俺在Ubuntu下是可以正常发音的,不知道是GoldenDict在Windows下本身的bug还是啥毛病,如果有JavaScript懂哥看到可以指点一下啊。

  另外,俺在Github也看到另外一个轮子,效果应该差不多,感兴趣的也可以试试。

谷歌

  基本原理相同,来源于:google-translate-for-goldendict。直接pip install google-translate-for-goldendict安装,然后在编辑->词典->程序里添加一个程序,名字填Google Translate,类型选Html,命令填python -m googletranslate zh-CN %GDWORD%

其他

  附送图标2个,献给和俺一样的强迫症选手:度盘链接,提取码: 95ef。

参考

用python实现有道翻译,配合Goldendict显示

YouDao4GoldenDict

WINDOWS下在GOLDENDICT中添加谷歌翻译

google-translate-for-goldendict

评论