python实现电子词典


Posted in Python onApril 23, 2020

本文实例为大家分享了python实现电子词典的具体代码,供大家参考,具体内容如下

# -*- coding: utf-8 -*-
#youdanTest.py
import urllib
import json
 
# 设置一个退出程序的出口
isOut = False
 
# 不断调用爬取翻译页面的功能
# 直到isOut被设置为True,退出程序
 
 
def query(keys):
 while True:
  if isOut == True:
   break
 
  # 假定用户输入“CloseMe”,则退出
  key = keys
  if key == "CloseMe":
   isOut = True
   continue # 回到循环开始处,然后结果条件满足退出
 
  # 做真正的查询操作
  url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null"
 
  # 构造headers
  headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
     "X-Requested-With": "XMLHttpRequest",
     "Accept": "application/json, text/javascript, */*; q=0.01",
     "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
     }
 
  # 把form数据转规范化,然后post给服务端
  formdata = {
   "i": key,
   "from": "AUTO",
   "to": "AUTO",
   "smartresult": "dict",
   "client": "fanyideskweb",
   "salt": "1523933959290",
   "sign": "248f5d216c45a64c38a3dccac0f4600d",
   "doctype": "json",
   "version": "2.1",
   "keyfrom": "fanyi.web",
   "action": "FY_BY_REALTIME",
   "typoResult": "false"
  }
  data = bytes(urllib.parse.urlencode(
      formdata),
      encoding="utf-8")
  # 给服务器发送post请求
  req = urllib.request.Request(url,
          data,
          headers,
          method="POST")
  response = urllib.request.urlopen(req)
  info = response.read().decode("utf-8")
  jsonLoads = json.loads(info)
  return jsonLoads['translateResult'][0][0]["tgt"]

服务端

#!/usr/bin/python3
# coding=utf-8
 
 
from signal import *
from socket import *
import pymysql
from time import *
import sys
import os
from youdaoTest import query
 
def do_child(connfd, db):
 while True:
  msg = connfd.recv(128).decode()
  print("msg : ", msg)
 
 
  if msg[0] == 'R':
   do_register(connfd, msg, db)
 
 
  if msg[0] == 'L':
   do_login(connfd, msg, db)
 
 
  if msg[0] == 'Q':
   do_query(connfd, msg, db)
 
 
  if msg[0] == 'H':
   do_history(connfd, msg, db)
 
 
  if msg[0] == 'E':
   connfd.close()
   sys.exit(0)
 return
 
def do_register(connfd, msg, db):
 print("in register.......")
 cursor = db.cursor()
 s = msg.split(' ')
 name = s[1]
 passwd = s[2]
 
 
 sql = "select * from user where name = '%s'" % name
 cursor.execute(sql)
 data = cursor.fetchone()
 print(data)
 
 
 if data != None:
  connfd.send("FALL".encode())
  return
 
 
 sql = "insert into user values ('%s','%s')" % (name, passwd)
 
 
 try:
  cursor.execute(sql)
  db.commit()
  connfd.send('OK'.encode())
 except:
  connfd.send("FALL".encode())
  db.rollback()
  return
 else:
  print("register OK !")

 
def do_login(connfd, msg, db):
 print("in login.......")
 cursor = db.cursor()
 s = msg.split(' ')
 name = s[1]
 passwd = s[2]
 
 
 try:
  sql = "select * from user where name = '%s' and passwd = '%s'" % (
   name, passwd)
  cursor.execute(sql)
  data = cursor.fetchone()
  print(data)
 except:
  pass
 if data == None:
  connfd.send("FALL".encode())
 else:
  connfd.send('OK'.encode())
 return
 
def do_query(connfd, msg, db):
 print("in query.......")
 start = time()
 cursor = db.cursor()
 s = msg.split(' ')
 words = s[1]
 name = s[2]
 msg = query(words)
 connfd.send(msg.encode())
 insert_history(db, words, name)
 
def do_history(connfd, msg, db):
 print('in history...')
 s = msg.split(' ')
 name = s[1]
 cursor = db.cursor()
 sql = 'select * from history where name = "%s"' % name
 try:
  cursor.execute(sql)
  data = cursor.fetchall()
  connfd.send('OK'.encode())
 except:
  connfd.send('FALL'.encode())
 sleep(0.1)
 for msg in data:
  name = msg[0]
  word = msg[1]
  time = msg[2]
  sleep(0.01)
  connfd.send(('%s %s %s' % (name, word, time)).encode())
 sleep(0.1)
 connfd.send('over'.encode())
 
def insert_history(db, words, name):
 time = ctime()
 cursor = db.cursor()
 sql = 'insert into history values ("%s","%s","%s")' % (name, words, time)
 try:
  cursor.execute(sql)
  db.commit()
 except:
  print('into history failed')
  db.rollback()
 
def main():
 signal(SIGCHLD, SIG_IGN)
 db = pymysql.connect('localhost', 'root', '123456', 'dict')
 
 
 HOST = sys.argv[1]
 PORT = int(sys.argv[2])
 sockfd = socket()
 sockfd.bind((HOST, PORT))
 sockfd.listen(5)
 
 while True:
  try:
   connfd, addr = sockfd.accept()
   print("connect addr : ", addr)
  except KeyboardInterrupt:
   raise
  except:
   continue
 
  pid = os.fork()
  if pid < 0:
   print("create child process failed")
   connfd.close()
   continue
  elif pid == 0:
   sockfd.close()
   do_child(connfd, db)
  else:
   connfd.close()
   continue
 
 db.close()
 sockfd.close()
 sys.exit(0)
 
if __name__ == "__main__":
 main()

电子词典客户端

#!/usr/bin/python
# coding=utf-8
 
from signal import *
from socket import *
from time import *
import sys
import os
 
 
def do_register(sockfd, msg):
 name = input("input your user name >>")
 passwd = input("input your user passwd >>")
 msg = 'R %s %s' % (name, passwd)
 
 sockfd.send(msg.encode())
 msg = sockfd.recv(128).decode()
 
 if msg[0:2] == 'OK':
  return 0
 else:
  return -1
 
 
def do_login(sockfd, msg):
 name = input("input your user name >>")
 passwd = input("input your user passwd >>")
 msg = 'L %s %s' % (name, passwd)
 
 sockfd.send(msg.encode())
 msg = sockfd.recv(128).decode()
 
 if msg[0:2] == 'OK':
  return name
 else:
  return -1
 
 
def do_query(sockfd, msg, name):
 while True:
  word = input("input word >>")
 
  if word == '##':
   return
 
  msg = 'Q %s %s' % (word, name)
 
  sockfd.send(msg.encode())
  msg = sockfd.recv(128).decode()
 
  if msg[0:2] == 'OK':
   msg = sockfd.recv(1024).decode()
   if msg == " ":
    print("not found this word")
   print(msg)
   # elif msg[:11] == 'found error':
   #  print('found error')
   #  continue
 
  else:
   print("fail to query")
   continue
 
 
def do_history(sockfd, msg, name):
 
 msg = 'H %s' % name
 sockfd.send(msg.encode())
 msg = sockfd.recv(128).decode()
 
 if msg[0:2] == 'OK':
  while True:
   data = sockfd.recv(1024).decode()
   if data == 'over':
    break
 
   print(data)
 else:
  print("fail to history")
  return -1
 
 
def main():
 HOST = sys.argv[1]
 PORT = int(sys.argv[2])
 msg = None
 
 sockfd = socket()
 
 sockfd.connect((HOST, PORT))
 
 def login(name):
  while True:
   print('''
   ==========query commend=========
   ---1:查词 2:历史记录 3:退出---
   ================================
   ''')
   try:
    cmd = int(input("Input commend >> "))
   except:
    print("Input error!")
    continue
 
   if cmd not in [1, 2, 3]:
    print("input error!")
    sys.stdin.flush()
    continue
 
   if cmd == 1:
    do_query(sockfd, msg, name)
   if cmd == 2:
    do_history(sockfd, msg, name)
   if cmd == 3:
    break
  return
 
 while True:
  print('''
  =============Welcome=============
  ----1: 注册 2: 登陆 3: 退出----
  =================================
  ''')
  try:
   cmd = int(input("Input command >> "))
  except:
   print("Input error")
   continue
 
  if cmd not in [1, 2, 3]:
   print("input error!")
   sys.stdin.flush()
   continue
 
  if cmd == 1:
   if do_register(sockfd, msg) == 0:
    print("register OK!")
   else:
    print("register FALL")
  if cmd == 2:
   name = do_login(sockfd, msg)
   if name != -1:
    print("login OK!")
    login(name)
   else:
    print("register FALL")
  if cmd == 3:
   msg = 'E'
   sockfd.send(msg.encode())
   sockfd.close()
   sys.exit(0)
 
 
if __name__ == "__main__":
 main()

查词时将单词发送到网络上,从有道中查询出单词翻译再返回给客户端。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python实现的一个自动售饮料程序代码分享
Aug 25 Python
Python查找相似单词的方法
Mar 05 Python
python利用urllib实现爬取京东网站商品图片的爬虫实例
Aug 24 Python
python3 遍历删除特定后缀名文件的方法
Apr 23 Python
python使用Plotly绘图工具绘制散点图、线形图
Apr 02 Python
python3+PyQt5 自定义窗口部件--使用窗口部件样式表的方法
Jun 26 Python
Python中变量的输入输出实例代码详解
Jul 28 Python
django基础学习之send_mail功能
Aug 07 Python
python pptx复制指定页的ppt教程
Feb 14 Python
django使用F方法更新一个对象多个对象字段的实现
Mar 28 Python
Python代码覆盖率统计工具coverage.py用法详解
Nov 25 Python
Django分页器的用法你都了解吗
May 26 Python
python中cPickle用法例子分享
Jan 03 #Python
使用python获取CPU和内存信息的思路与实现(linux系统)
Jan 03 #Python
Python群发邮件实例代码
Jan 03 #Python
python切换hosts文件代码示例
Dec 31 #Python
使用Python进行稳定可靠的文件操作详解
Dec 31 #Python
python连接mongodb操作数据示例(mongodb数据库配置类)
Dec 31 #Python
python连接mysql数据库示例(做增删改操作)
Dec 31 #Python
You might like
解析PHP中的unset究竟会不会释放内存
2013/07/18 PHP
php计算函数执行时间的方法
2015/03/20 PHP
php文件上传 你真的掌握了吗
2016/11/28 PHP
微信封装的调用微信签名包的类库
2017/06/08 PHP
修改jQuery Validation里默认的验证方法
2012/02/14 Javascript
关于jQuery中.attr()和.prop()的问题探讨
2013/09/06 Javascript
jquery获取元素值的方法(常见的表单元素)
2013/11/15 Javascript
JavaScript判断变量是否为undefined的两种写法区别
2013/12/04 Javascript
对Jquery中的ajax再封装,简化操作示例
2014/02/12 Javascript
javascript中的this详解
2014/12/08 Javascript
JS动态修改iframe内嵌网页地址的方法
2015/04/01 Javascript
JavaScript实现点击文字切换登录窗口的方法
2015/05/11 Javascript
详细解读AngularJS中的表单验证编程
2015/06/19 Javascript
微信jssdk在iframe页面失效问题的解决措施
2016/03/03 Javascript
JS上传图片预览插件制作(兼容到IE6)
2016/08/07 Javascript
js完整倒计时代码分享
2016/09/18 Javascript
jQuery.cookie.js实现记录最近浏览过的商品功能示例
2017/01/23 Javascript
node.js实现回调的方法示例
2017/03/01 Javascript
简单理解Vue中的nextTick方法
2018/01/30 Javascript
解决koa2 ctx.render is not a function报错问题
2018/08/07 Javascript
JQuery中的常用事件、对象属性与使用方法分析
2019/12/23 jQuery
vue使用better-scroll实现滑动以及左右联动
2020/06/30 Javascript
[01:03:22]LGD vs OG 2018国际邀请赛淘汰赛BO3 第一场 8.25
2018/08/29 DOTA
python自动化测试之从命令行运行测试用例with verbosity
2014/09/28 Python
python中Switch/Case实现的示例代码
2017/11/09 Python
Python学习笔记之For循环用法详解
2019/08/14 Python
DataFrame.to_excel多次写入不同Sheet的实例
2019/12/02 Python
利用setuptools打包python程序的方法步骤
2020/01/18 Python
Python GUI库PyQt5样式QSS子控件介绍
2020/02/25 Python
小孩百日宴答谢词
2014/01/15 职场文书
社团活动总结书
2014/06/27 职场文书
普通党员四风问题对照检查材料
2014/09/27 职场文书
工艺技术员岗位职责
2015/02/04 职场文书
2016年共产党员个人承诺书
2016/03/24 职场文书
SQL 尚未定义空闲 CPU 条件 - OnIdle 作业计划将不起任何作用
2021/06/30 SQL Server
python高温预警数据获取实例
2022/07/23 Python