python:mdict + bottle = web 查询英汉词典

用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('/')
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('{txt} is not in word_list."
    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 数据




    
    
       
    查询英汉词典 
    



  

运行 python mdict_bottle.py

浏览器访问 http://localhost:8888/

你可能感兴趣的:(python,web服务,javascript,python,bottle,jquery,json)