本文实例为大家分享了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" # 构造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()
查词时将单词发送到网络上,从有道中查询出单词翻译再返回给客户端。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
暂无评论...
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。
更新日志
2024年11月24日
2024年11月24日
- 凤飞飞《我们的主题曲》飞跃制作[正版原抓WAV+CUE]
- 刘嘉亮《亮情歌2》[WAV+CUE][1G]
- 红馆40·谭咏麟《歌者恋歌浓情30年演唱会》3CD[低速原抓WAV+CUE][1.8G]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[320K/MP3][193.25MB]
- 【轻音乐】曼托凡尼乐团《精选辑》2CD.1998[FLAC+CUE整轨]
- 邝美云《心中有爱》1989年香港DMIJP版1MTO东芝首版[WAV+CUE]
- 群星《情叹-发烧女声DSD》天籁女声发烧碟[WAV+CUE]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[FLAC/分轨][748.03MB]
- 理想混蛋《Origin Sessions》[320K/MP3][37.47MB]
- 公馆青少年《我其实一点都不酷》[320K/MP3][78.78MB]
- 群星《情叹-发烧男声DSD》最值得珍藏的完美男声[WAV+CUE]
- 群星《国韵飘香·贵妃醉酒HQCD黑胶王》2CD[WAV]
- 卫兰《DAUGHTER》【低速原抓WAV+CUE】
- 公馆青少年《我其实一点都不酷》[FLAC/分轨][398.22MB]
- ZWEI《迟暮的花 (Explicit)》[320K/MP3][57.16MB]