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 相关文章推荐
在Windows8上的搭建Python和Django环境
Jul 03 Python
python冒泡排序简单实现方法
Jul 09 Python
Python cookbook(数据结构与算法)找到最大或最小的N个元素实现方法示例
Feb 13 Python
python表格存取的方法
Mar 07 Python
python pandas dataframe 行列选择,切片操作方法
Apr 10 Python
PyQt5每天必学之单行文本框
Apr 19 Python
Flask框架Jinjia模板常用语法总结
Jul 19 Python
NumPy 数组使用大全
Apr 25 Python
python中struct模块之字节型数据的处理方法
Aug 27 Python
Python安装依赖(包)模块方法详解
Feb 14 Python
python代码xml转txt实例
Mar 10 Python
Python venv虚拟环境配置过程解析
Jul 08 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
Wordpress php 分页代码
2009/10/21 PHP
解析PHPExcel使用的常用说明以及把PHPExcel整合进CI框架的介绍
2013/06/24 PHP
ThinkPHP自动转义存储富文本编辑器内容导致读取出错的解决方法
2014/08/08 PHP
php简单判断两个字符串是否相等的方法
2015/07/13 PHP
JSON序列化与解析原生JS方法且IE6和chrome测试通过
2013/09/05 Javascript
兼容所有浏览器的js复制插件Zero使用介绍
2014/03/19 Javascript
jQuery的animate函数学习记录
2014/08/08 Javascript
JS实现的倒计时效果实例(2则实例)
2015/12/23 Javascript
使用openSpeDiv方法实现Ecshop登录弹窗框效果
2017/03/13 Javascript
微信小程序实现图片上传
2019/05/23 Javascript
Layui数据表格判断编辑输入的值,是否为我需要的类型详解
2019/10/26 Javascript
浅谈实现在线预览PDF的几种解决办法
2020/08/10 Javascript
react项目从新建到部署的实现示例
2021/02/19 Javascript
Python获取DLL和EXE文件版本号的方法
2015/03/10 Python
用virtualenv建立多个Python独立虚拟开发环境
2017/07/06 Python
微信小程序跳一跳游戏 python脚本跳一跳刷高分技巧
2018/01/04 Python
Python rstrip()方法实例详解
2018/11/11 Python
python SocketServer源码深入解读
2019/09/17 Python
python实现小程序推送页面收录脚本
2020/04/20 Python
基于python和flask实现http接口过程解析
2020/06/15 Python
python爬虫beautifulsoup解析html方法
2020/12/07 Python
使用HTML5 Canvas API绘制弧线的教程
2016/03/22 HTML / CSS
浅谈html5 video 移动端填坑记
2018/01/15 HTML / CSS
印尼第一大家居、生活和家具电子商务:Ruparupa
2019/11/25 全球购物
面向对象编程是如何提高软件开发水平的
2014/05/06 面试题
函授毕业生自我鉴定
2013/11/06 职场文书
实习生自我评价
2014/01/18 职场文书
人事任命书怎么写
2014/06/05 职场文书
优秀教师先进个人事迹材料
2014/08/31 职场文书
检察机关个人对照检查材料
2014/09/15 职场文书
单位工作证明
2014/10/07 职场文书
2015年幼儿园后勤工作总结
2015/04/25 职场文书
2015年大学生暑期实习报告
2015/07/13 职场文书
30岁前绝不能错过的10本书
2019/08/08 职场文书
导游词之大雁塔景区
2019/09/17 职场文书
一级电子管军用接收机测评
2022/04/05 无线电