用chrome 访问 https://www.lfd.uci.edu/~gohlke/pythonlibs/#python-lzo
下载 python_lzo-1.12-cp37-cp37m-win_amd64.whl
pip install /pypi/python_lzo-1.12-cp37-cp37m-win_amd64.whl
pip install readmdict ; 参见:使用Python调用mdx字典文件进行查词
安装 Mdict 去 MDict
pip install bottle
mdict_bottle.py
# -*- coding: utf-8 -*-
""" web server 用于查询英汉词典 """
import os
import sys
import json
import time
from readmdict import MDX
from bottle import route, run, post, request, static_file
os.chdir("/mdict")
start_time = time.time()
# 加载.mdx文件
filename = "your.mdx"
mdx = MDX(filename)
headwords = [*mdx] # 单词名列表
items = [*mdx.items()] # 释义html源码列表
n = len(headwords)
m = len(items)
if n == m:
print(f'{filename} 加载成功:共{n}条')
end_time = time.time()
print('cost %f second' % (end_time - start_time))
else:
print(f'ERROR:加载失败 {n}!={m}')
sys.exit(1)
@route('/')
def server_static(filepath="index.html"):
return static_file(filepath, root='./')
# 静态资源的目录通常称为public或static
@route('/<filepath:path>')
def server_static(filepath):
return static_file(filepath, root='./')
def eng_han(txt):
""" 英译中 """
if not txt.isascii():
return 'Maybe text is not english'
word = txt.encode()
word1 = txt.capitalize().encode() # 第1个字母变大写
global headwords, items
try: # 查词,返回单词和html文件
if word in headwords:
wordIndex = headwords.index(word)
else:
wordIndex = headwords.index(word1)
word,html = items[wordIndex]
result = html.decode()
result = result.replace('<img src="','<img src="/data/')
result = result.replace('"/thumb/', '"data/thumb/')
result = result.replace('entry://', '/trans?txt=')
#result = result.replace('sound://','"/data/')
except:
result = f"<h3>{txt} is not in word_list.</h3>"
return result
@route('/prefix')
def prefix():
""" 前缀匹配 """
try:
txt = request.query.txt
except:
return '1: get txt error'
if len(txt.strip()) ==0:
return 'text is null'
print(txt)
if len(txt) > 1:
alist = []
word = txt.strip().lower() # 字母变小写
for hw in headwords:
hws = hw.decode().lower()
if hws.startswith(word):
hws = hw.decode()
alist.append(hws)
if len(alist) > 0:
result = json.dumps(alist)
else:
result = '["not found"]'
else:
result = '["length too short"]'
return result
@route('/trans')
def trans():
""" method=GET 英译中"""
try:
txt = request.query.txt
except:
return '1: get txt error'
if len(txt.strip()) ==0:
return 'text is null'
print(txt)
result = eng_han(txt)
return result
@route('/trans', method='POST')
def trans():
""" 英译中 """
try:
#txt = request.forms.get('txt')
txt = request.POST.get('txt')
except:
return '1: get txt error'
if len(txt.strip()) ==0:
return 'text is null'
print(txt)
result = eng_han(txt)
return result
run(host='localhost', port=8888, debug=True)
index.html 用 jQuery.getJSON 处理 json 数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>查询英汉词典</title>
<script src="jquery-3.2.1.min.js"></script>
<style>
/* portrait 判断为竖屏 */
@media only screen and (orientation: portrait){
#lab1 {display:none;}
}
/* landscape 判断为横屏 */
@media only screen and (orientation: landscape){
#lab1 {display: ;}
}
</style>
</head>
<body>
<form name="form" id="form" action="trans" method="POST" target="iframe">
<label id="lab1">请输入:</label>
<input type="text" name="txt" id='txt' size="30" placeholder="请输入 a word">
<input type="submit" name="eng_han" value="英译汉">
<input type="button" name="btn1" id="btn1" value="前缀查询">
</form>
<p></p>
<div style="float:left; width:100%;">
<div id="result" style="float:left; width:80%; height:400; border:2px;">
<iframe name="iframe" id="iframe" width="100%" height="400"> </iframe>
</div>
<div id="alist" style="float:right; width:20%; height:400; border:2px;">
</div>
</div>
<audio id="sound" controls autoplay> </audio>
<script type="text/javascript">
$(function(){
$("#btn1").click(function(){
$.getJSON("/prefix?txt="+$("#txt").val(), function(data){
var items = [];
$.each(data, function(i, item){
if (i<=20){
items[i] = '<a href="/trans?txt=' +item+ '" target="iframe">' +item+ "</a><br>";
}
});
var a = items.join('\n');
if (a) $('#alist').html(a);
})
})
});
// 页面加载添加:监听iframe网页点击事件
$(document).ready(function(){
var listener = window.addEventListener('blur', function(){
if (document.activeElement === document.getElementById('iframe')){
$('iframe').contents().find('a.fayin').click(function(event){
event.preventDefault();
var a = $(this);
if (a){
var addr = a.attr('href');
if (addr.indexOf('sound://')==0){
var audio = document.getElementById("sound");
audio.src = "/data" + addr.substring(7);
if (audio.paused) audio.play();
} else {
alert('href='+addr);
}
}
})
}
});
});
</script>
</body>
</html>
运行 python mdict_bottle.py
浏览器访问 http://localhost:8888/