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

该文章描述了一个使用PythonFlask框架搭建的Web服务,用于查询英汉词典和汉英翻译。服务依赖于readmdict库处理Mdict字典文件,pinyin库进行拼音转换,snownlp库进行中文处理。用户可以通过输入文本进行翻译,支持首字母匹配和英文单词查询。
摘要由CSDN通过智能技术生成

用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 pinyin; 

pip install snownlp;

pip install flask
pip install readmdict ; 参见:使用Python调用mdx字典文件进行查词

下载 Mdict 去 MDict

mdict_flask.py

# -*- coding: utf-8 -*-
""" web server 用于查询英汉词典,汉英词典 """
import os
import sys
from readmdict import MDX
import pinyin
from pinyin import cedict
import snownlp
from flask import Flask, request, render_template

# 初始化 汉英词典
cedict.init()

os.chdir("/flask")
# 加载.mdx文件
filename = "/mdict/21世纪大英汉词典.mdx"
mdx = MDX(filename)
headwords = [*mdx]       # 单词名列表
items = [*mdx.items()]   # 释义html源码列表
n = len(headwords)
m = len(items)
if n == m:
    print(f'{filename} 加载成功:共{n}条')
else:
    print(f'ERROR:加载失败 {n}!={m}')
    sys.exit(1)

app = Flask(__name__)

@app.route('/')
def index():
    return render_template("index.html")

@app.route('/trans', methods=['POST'])
def trans():
    """ 英译中 """
    result = ''
    if request.method == 'POST':
        try:
            txt = request.form['txt']
        except:
            return '1: get txt error'
        if len(txt.strip()) ==0:
            return 'text is null'
        print(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('sf_ecce.css','/static/sf_ecce.css')
        except:
            result = f"<h3>{txt} is not in word_list.</h3>"
            if len(txt) > 3:
                # prefix search
                alist = []
                word = txt.strip().lower() # 字母变小写
                for hw in headwords:
                    hws = hw.decode().lower()
                    if hws.startswith(word):
                        alist.append(hw.decode())
                if len(alist) > 0:
                    result = '<h3>'+ ', '.join((alist)) +'</h3>'
            else:
                result = f"{txt} length too short.(length>3)"
    return result

@app.route('/tran2', methods=['POST'])
def tran2():
    """ 中译英 """
    result = ''
    try:
        txt = request.form['txt']
    except:
        return '2: get txt error'
    if len(txt.strip()) ==0:
        return 'text is null'
    print(txt)
    if txt.isascii():
        return 'Maybe text is English'
    wlist = snownlp.SnowNLP(txt).words
    pinyins = snownlp.SnowNLP(txt).pinyin
    words = ' '.join(wlist)
    pyin = pinyin.get(words)
    result += pyin +'<br>\n'
    result += ' '.join((pinyins)) +'\n<p>\n'
    for w in wlist:
        english = cedict.translate_word(w, dictionary=['simplified'])
        result +=  f"{w}: {english}" +'<br>\n'
    return result

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8888, debug=True)

./templates/index.html

<!DOCTYPE html>
<html>
<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>
    <link rel="stylesheet" type="text/css" href="/static/sf_ecce.css"/>
    <script type="text/javascript">
	  function trans(){ form.action="trans"; form.submit();}
      function tran2(){ form.action="tran2"; form.submit();}
    </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="search" name="txt" size="30" placeholder="请输入中文或 word">
    <input type="button" name="btn1" onclick="trans();" value="英译汉">
	<input type="button" name="btn2" onclick="tran2();" value="汉译英">
  </form>
  <p></p>
<div id="result">
  <iframe name="iframe" id="iframe" width="90%" height="400"> </iframe>
</div>
</body>
</html>

运行 python mdict_flask.py 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值