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

评论

3D cell culture 3D cell culturing 3D cell microarrays 3D culture 3D culture model 3D printing 3D spheroid 3D tumor culture 3D tumors 3D vascular mapping ACT ADV AUTODESK Abdominal wall defects Acoustofluidics Adipocyte Adipogenesis Adoptive cell therapy AirPods Alginate Anticancer Anticancer agents Anticancer drugs Apple Apriori Association Analysis August AutoCAD Autodock Vina Bio-inspired systems Biochannels Bioengineering Bioinspired Biological physics Biomarkers Biomaterial Biomaterials Biomimetic materials Biomimetics Bioprinting Blood purification Blood-brain barrier Bone regeneration Breast cancer Breast cancer cells Breast neoplasms CM1860 CRISPR/Cas9 system CSS CTC isolation CTCs Cancer Cancer angiogenesis Cancer cell invasion Cancer immunity Cancer immunotherapy Cancer metabolism Cancer metastasis Cancer models Cancer screening Cancer stem cells Cell adhesion Cell arrays Cell assembly Cell clusters Cell culture Cell culture techniques Cell mechanical stimulation Cell morphology Cell trapping Cell-bead pairing Cell-cell interaction Cell-laden gelatin methacrylate Cellular uptake Cell−cell interaction Cervical cancer Cheminformatics Chemotherapy Chimeric antigen receptor-T cells Chip interface Circulating tumor cells Clinical diagnostics Cmder Co-culture Coculture Colon Colorectal cancer Combinatorial drug screening Combinatorial drug testing Compartmentalized devices Confined migration Continuous flow Convolutional neural network Cooking Crawler Cryostat Curved geometry Cytokine detection Cytometry Cytotoxicity Cytotoxicity assay DESeq DNA tensioners Data Mining Deep learning Deformability Delaunay triangulation Detective story Diabetic wound healing Diagnostics Dielectrophoresis Differentiation Digital microfluidics Direct reprogramming Discrimination of heterogenic CTCs Django Double emulsion microfluidics Droplet Droplet microfluidics Droplets generation Droplet‐based microfluidics Drug combination Drug efficacy evaluation Drug evaluation Drug metabolism Drug resistance Drug resistance screening Drug screening Drug testing Dual isolation and profiling Dynamic culture Earphone Efficiency Efficiency of encapsulation Elastomers Embedded 3D bioprinting Encapsulation Endothelial cell Endothelial cells English Environmental hazard assessment Epithelial–mesenchymal transition Euclidean distance Exosome biogenesis Exosomes Experiment Extracellular vesicles FC40 FP-growth Fabrication Fast prototyping Fibroblasts Fibrous strands Fiddler Flask Flow rates Fluorescence‐activated cell sorting Functional drug testing GEO Galgame Game Gene Expression Profiling Gene delivery Gene expression profiling Gene targetic Genetic association Gene‐editing Gigabyte Glypican-1 GoldenDict Google Translate Gradient generator Growth factor G‐CSF HBEXO-Chip HTML Hanging drop Head and neck cancer Hectorite nanoclay Hepatic models Hepatocytes Heterotypic tumor HiPSCs High throughput analyses High-throughput High-throughput drug screening High-throughput screening assays High‐throughput methods Histopathology Human neural stem cells Human skin equivalent Hydrogel Hydrogel hypoxia Hydrogels ImageJ Immune checkpoint blockade Immune-cell infiltration Immunoassay Immunological surveillance Immunotherapy In vitro tests In vivo mimicking Induced hepatocytes Innervation Insulin resistance Insulin signaling Interferon‐gamma Intestinal stem cells Intracellular delivery Intratumoral heterogeneity JRPG Jaccard coefficient JavaScript July June KNN Kidney-on-a-chip Lab-on-a-chip Laptop Large scale Lattice resoning Leica Leukapheresis Link Lipid metabolism Liquid biopsy Literature Liver Liver microenvironment Liver spheroid Luminal mechanics Lung cells MOE Machine Learning Machine learning Macro Macromolecule delivery Macroporous microgel scaffolds Magnetic field Magnetic sorting Malignant potential Mammary tumor organoids Manhattan distance Manual Materials science May Mechanical forces Melanoma Mesenchymal stem cells Mesoporous silica particles (MSNs) Metastasis Microassembly Microcapsule Microcontact printing Microdroplets Microenvironment Microfluidic array Microfluidic chips Microfluidic device Microfluidic droplet Microfluidic organ-on-a chip Microfluidic organ-on-a-chip Microfluidic patterning Microfluidic screening Microfluidic tumor models Microfluidic-blow-spinning Microfluidics Microneedles Micropatterning Microtexture Microvascular Microvascular networks Microvasculatures Microwells Mini-guts Mirco-droplets Molecular docking Molecular imprinting Monolith Monthly Multi-Size 3D tumors Multi-organoid-on-chip Multicellular spheroids Multicellular systems Multicellular tumor aggregates Multi‐step cascade reactions Myeloid-derived suppressor cells NK cell NanoZoomer Nanomaterials Nanoparticle delivery Nanoparticle drug delivery Nanoparticles Nanowell Natural killer cells Neural progenitor cell Neuroblastoma Neuronal cell Neurons Nintendo Nissl body Node.js On-Chip orthogonal Analysis OpenBabel Organ-on-a-chip Organ-on-a-chip devices Organically modified ceramics Organoids Organ‐on‐a‐chip Osteochondral interface Oxygen control Oxygen gradients Oxygen microenvironments PDA-modified lung scaffolds PDMS PTX‐loaded liposomes Pain relief Pancreatic cancer Pancreatic ductal adenocarcinoma Pancreatic islet Pathology Patient-derived organoid Patient-derived tumor model Patterning Pearl powder Pearson coefficient Penetralium Perfusable Personalized medicine Photocytotoxicity Photodynamic therapy (PDT) Physiological geometry Pluronic F127 Pneumatic valve Poetry Polymer giant unilamellar vesicles Polystyrene PowerShell Precision medicine Preclinical models Premetastatic niche Primary cell transfection Printing Protein patterning Protein secretion Pubmed PyMOL Pybel Pytesseract Python Quasi-static hydrodynamic capture R RDKit RNAi nanomedicine RPG Reactive oxygen species Reagents preparation Resistance Review Rod-shaped microgels STRING Selective isolation Self-assembly Self-healing hydrogel September Signal transduction Silk-collagen biomaterial composite Similarity Single cell Single cells Single molecule Single-cell Single-cell RNA sequencing Single‐cell analysis Single‐cell printing Size exclusion Skin regeneration Soft lithography Softstar Spheroids Spheroids-on-chips Staining StarBase Stem cells Sub-Poisson distribution Supramolecular chemistry Surface chemistry Surface modification Switch T cell function TCGA Tanimoto coefficient The Millennium Destiny The Wind Road Thin gel Tissue engineering Transcriptome Transfection Transient receptor potential channel modulators Tropism Tubulogenesis Tumor environmental Tumor exosomes Tumor growth and invasion Tumor immunotherapy Tumor metastasis Tumor microenvironment Tumor response Tumor sizes Tumor spheroid Tumor-on-a-chip Tumorsphere Tumors‐on‐a‐chip Type 2 diabetes mellitus Ultrasensitive detection Unboxing Underlying mechanism Vascularization Vascularized model Vasculature Visual novel Wettability Windows Terminal Word Writing Wuxia Xenoblade Chronicles Xin dynasty XuanYuan Sword Youdao cnpm fsevents miR-125b-5p miR-214-3p miRNA signature miRanda npm
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×