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合并多个装饰器小技巧
Apr 28 Python
Python创建模块及模块导入的方法
May 27 Python
Python实现TCP/IP协议下的端口转发及重定向示例
Jun 14 Python
Python实现合并两个列表的方法分析
May 28 Python
python-pyinstaller、打包后获取路径的实例
Jun 10 Python
用vue.js组件模拟v-model指令实例方法
Jul 05 Python
python爬虫刷访问量 2019 7月
Aug 01 Python
python列表返回重复数据的下标
Feb 10 Python
Python selenium抓取虎牙短视频代码实例
Mar 02 Python
python模拟哔哩哔哩滑块登入验证的实现
Apr 24 Python
python 检测nginx服务邮件报警的脚本
Dec 31 Python
PyCharm配置KBEngine快速处理代码提示冲突、配置命令问题
Apr 03 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 URL地址获取函数代码(端口等) 推荐
2010/05/15 PHP
Windows下XDebug 手工配置与使用说明
2010/07/11 PHP
php smarty截取中文字符乱码问题?gb2312/utf-8
2011/11/07 PHP
PHP教程之PHP中shell脚本的使用方法分享
2012/02/23 PHP
php利用事务处理转账问题
2015/04/22 PHP
PHP打印输出函数汇总
2016/08/28 PHP
js文字滚动停顿效果代码
2008/06/28 Javascript
Jquery 1.42 checkbox 全选和反选代码
2010/03/27 Javascript
JavaScript中switch判断容易犯错的一个细节
2014/08/27 Javascript
node.js中的buffer.Buffer.isEncoding方法使用说明
2014/12/14 Javascript
深入分析jsonp协议原理
2015/09/26 Javascript
jQuery实现鼠标选文字发新浪微博的方法
2016/04/02 Javascript
分享两段简单的JS代码防止SQL注入
2016/04/12 Javascript
JavaScript正则表达式exec/g实现多次循环用法示例
2017/01/17 Javascript
JavaScript实现公历转农历功能示例
2017/02/13 Javascript
原生JavaScript实现Tooltip浮动提示框特效
2017/03/07 Javascript
原生JavaScript实现Ajax异步请求
2017/11/19 Javascript
Vuex,iView UI面包屑导航使用扩展详解
2019/11/04 Javascript
微信小程序图片自适应实现解析
2020/01/21 Javascript
[01:36:57]【09DOTA2第一视角】小骷髅
2014/04/16 DOTA
[06:50]DSPL次级职业联赛十强晋级之路
2014/11/18 DOTA
[47:50]Secret vs VP 2018国际邀请赛小组赛BO2 第二场 8.17
2018/08/20 DOTA
Python基于Pymssql模块实现连接SQL Server数据库的方法详解
2017/07/20 Python
python验证码识别教程之利用滴水算法分割图片
2018/06/05 Python
Python API len函数操作过程解析
2020/03/05 Python
通过Python实现Payload分离免杀过程详解
2020/07/13 Python
python Zmail模块简介与使用示例
2020/12/19 Python
UNIX特点都有哪些
2016/04/05 面试题
小学教师的个人自我鉴定
2013/10/26 职场文书
校友会欢迎辞
2014/01/13 职场文书
上课迟到检讨书
2014/02/19 职场文书
亲子阅读的活动方案
2014/08/15 职场文书
学习党的群众路线剖析材料
2014/10/09 职场文书
2015年煤矿工作总结
2015/04/28 职场文书
Python爬取用户观影数据并分析用户与电影之间的隐藏信息!
2021/06/29 Python
golang的文件创建及读写操作
2022/04/14 Golang