PyWebIO 模仿 mdict 查英汉词典

PyWebIO提供了一系列命令式的交互函数来在浏览器上获取用户输入和进行输出,将浏览器变成了一个“富文本终端”,可以用于构建简单的Web应用或基于浏览器的GUI应用。 使用PyWebIO,开发者能像编写终端脚本一样(基于input 和 put 进行交互)来编写应用,无需具备HTML和 js的相关知识; PyWebIO还可以方便地整合进现有的Web服务。非常适合快速构建对UI要求不高的应用。

 参考 :PyWebIO 中文文档

用chrome 访问 https://www.lfd.uci.edu/~gohlke/pythonlibs/#python-lzo
下载 python_lzo-1.14-cp38-cp38-win_amd64.whl
pip install python_lzo-1.14-cp38-cp38-win_amd64.whl

pip install readmdict ;

pip install pywebio

pywebio-1.8.2.tar.gz (495 kB)
tornado-6.2-cp37-abi3-win_amd64.whl (425 kB)
user_agents-2.2.0-py3-none-any.whl (9.6 kB)
ua_parser-0.18.0-py2.py3-none-any.whl (38 kB)

编写 mdict_pywebio.py 如下:

# -*- coding: utf-8 -*-
""" 查询英汉 lexicons """
import os
import time
from readmdict import MDX
from pywebio import config
from pywebio.input import input, TEXT, select
from pywebio.output import put_html

def open_mdx():
    """ 读.mdx词典文件 """
    start_time = time.time()
    global headwords, items
    os.chdir("/mdict/")
    # 加载.mdx文件
    fname = "your.mdx"
    mdx = MDX(fname)
    headwords = [*mdx]       # 单词名列表
    items = [*mdx.items()]   # 释义html源码列表
    end_time = time.time()
    print('cost %f second' % (end_time - start_time))

def prefix(txt):
    """ 前缀匹配 """
    global headwords
    try:
        type(headwords)
    except NameError:
        print('headwords is undefined.')
        return
    alist = []    
    if len(txt) > 1:
        word = txt.strip().lower() # 字母变小写
        for hw in headwords:
            hws = hw.decode().lower()
            if hws.startswith(word):
                alist.append(hw.decode())
    else:
        print(f"{txt} input too short")
    return alist

def query1(txt):
    """  查询英文单词 """
    global headwords
    try:
        type(headwords)
    except NameError:
        print('headwords is undefined.')
        return
    word = txt.lower().encode()
    word1 = txt.capitalize().encode() # 第1个字母变大写
    try: # 查词,返回单词和html文件
        if word in headwords:
            wordIndex = headwords.index(word)
        else:
            wordIndex = headwords.index(word1)
        word,html = items[wordIndex]
        result = html.decode()
        return result
    except:
        return f"{txt} is not in word_list."

if __name__ == '__main__':
    open_mdx()
    txt = input("请输入 a word", type=TEXT)
    alist = prefix(txt)
    word = select("请选择 a word", options=alist)
    result = query1(word)
    #pywebio.config(title="result", cssfile="your.css")
    if result:
        put_html(result)
    else:
        print("result is null")

把你的词典 css文件 copy to web主目录 在 D:\Python38\Lib\site-packages\pywebio\html\

运行 python mdict_pywebio.py

你可能感兴趣的:(python,python,pywebio,readmdict)