Python implements electronic dictionary

The examples in this article share the specific code for implementing electronic dictionary in python for your reference. The specific content is as follows

Server

#! /usr/bin/env python3
from __future__ import unicode_literals
# coding=utf-8from socket import*import os
import pymysql
import time
import sys
import signal
DICT_TEXT ="./dict.txt"
HOST ='0.0.0.0'
PORT =8000
ADDR =(HOST, PORT)
# Main control flow
def main():
# Connect to the database
db = pymysql.connect\
(' localhost','root','123456','dict')
# Create a streaming socket
s =socket()
s.setsockopt(SOL_SOCKET, SO_REUSEADDR,1)
s.bind(ADDR)
s.listen(5)
# Or omit the child process exit
signal.signal(signal.SIGCHLD, signal.SIG_IGN)while True:try:
c, addr = s.accept()print("Connect from", addr)
except KeyboardInterrupt:
s.close()
sys.exit("Server exit")
except Exception as e:print(e)continue
# Create a child process to handle client requests
pid = os.fork()if pid ==0:
s.close()do_child(c, db)else:
c.close()
def do_child(c, db):
# Receiving requests in a loop
while True:
data = c.recv(128).decode()print("Request:", data)if(not data) or data[0]=='E':
c.close()
sys.exit(0)
elif data[0]=='R':do_register(c, db, data)
elif data[0]=="L":do_login(c, db, data)
elif data[0]=='Q':do_query(c, db, data)
elif data[0]=='H':do_history(c, db, data)
def do_register(c, db, data):
l = data.split(' ')
name = l[1]
passwd = l[2]
cursor = db.cursor()
sql = \
" select * from user where name='%s'"% name
cursor.execute(sql)
r = cursor.fetchone()if r != None:
c.send(b'EXISTS')return
sql ="insert into user (name,passwd)\
values ('%s','%s')"%(name, passwd)try:
cursor.execute(sql)
db.commit()
c.send(b'OK')
except:
db.rollback()
c.send(b'FALL')returnelse:print("%s registered successfully"% name)
def do_login(c, db, data):
l = data.split(' ')
name = l[1]
passwd = l[2]
cursor = db.cursor()
sql ="select * from user where \
name='%s' and passwd='%s'"%(name, passwd)
cursor.execute(sql)
r = cursor.fetchone()if r == None:
c.send('Incorrect username or password'.encode())else:
c.send(b'OK')
def do_query(c, db, data):
l = data.split(' ')
name = l[1]
word = l[2]
cursor = db.cursor()
def insert_history():
tm = time.ctime()
sql ="insert into hist (name,word,time)\
values ('%s','%s','%s')"%(name, word, tm)try:
cursor.execute(sql)
db.commit()
except:
db.rollback()returntry:
f =open(DICT_TEXT,'rb')
except:
c.send("500 server exception".encode())returnwhile True:
line = f.readline().decode()
w = line.split(' ')[0]if(not line) or w   word:
c.send("The word was not found".encode())break
elif w == word:
c.send(b'OK')
time.sleep(0.1)
c.send(line.encode())insert_history()break
f.close()
def do_history(c, db, data):
name = data.split(' ')[1]
cursor = db.cursor()try:
sql ="select * from hist \
where name='%s'"% name
cursor.execute(sql)
r = cursor.fetchall()if not r:
c.send('No history'.encode())returnelse:
c.send(b'OK')
except:
c.send("Database query error".encode())return
n =0for i in r:
n +=1
# Show up to 10
if n   10:break
time.sleep(0.1)
msg ="%s %s %s"%(i[1], i[2], i[3])
c.send(msg.encode())
time.sleep(0.1)
c.send(b'##')if __name__ =="__main__":main()

Client

#! /usr/bin/env python3
# coding=utf-8from socket import*import sys 
import getpass
def main():iflen(sys.argv)<3:print("argv is error")return
HOST = sys.argv[1]
PORT =int(sys.argv[2])
ADDR =(HOST,PORT)
s =socket()
s.connect(ADDR)while True:print('''\n
=========== Welcome=========--1.Registration 2.Login 3.drop out--===========================''')try:
cmd =int(input("Input options"))
except Exception:print("Input command error")continueif cmd not in[1,2,3]:print("Sorry, there is no such order")
sys.stdin.flush() #Clear input
continue 
elif cmd ==1:
name =do_register(s)if name !=1:print("registration success,Direct Login!")login(s,name)else:print("registration failed!")
elif cmd ==2:
name =do_login(s)if name !=1:print("login successful!")login(s,name)else:print("Login failed!")
elif cmd ==3:
s.send(b"E")
sys.exit("Thanks for using")
def do_register(s):while True:
name =input("username:")
passwd = getpass.getpass("password:")
passwd1 = getpass.getpass("confirm password:")if(' 'in name)or(' 'in passwd):print("No spaces in username and password")continueif passwd != passwd1:print("The two passwords are not consistent")continue
msg ="R {} {}".format(name,passwd)
# send request
s.send(msg.encode())
# Receive reply
data = s.recv(128).decode()if data =="OK":return name
elif data =='EXISTS':print("The user already exists")return1else:return1
def do_login(s):
name =input("username:")
passwd = getpass.getpass("password:")
msg ="L {} {}".format(name,passwd)
s.send(msg.encode())
data = s.recv(128).decode()if data =='OK':return name
else:print(data)return1
def login(s,name):while True:print('''\n
=========== Query interface============1.Lookup 2.History 3.Logout
=============================''') try:
cmd =int(input("Input options"))
except Exception:print("Command error")continueif cmd not in[1,2,3]:print("Sorry, there is no such order")
sys.stdin.flush() #Clear input
continue 
elif cmd ==1:do_query(s,name)
elif cmd ==2:do_history(s,name)
elif cmd ==3:return
def do_query(s,name):while True:
word =input("word:")if word =="##":break 
msg ="Q {} {}".format(name,word)
s.send(msg.encode())
data = s.recv(128).decode()if data =='OK':
data = s.recv(2048).decode()print(data)else:print(data)
def do_history(s,name):
msg ="H {}".format(name)
s.send(msg.encode())
data = s.recv(128).decode()if data =='OK':while True:
data = s.recv(1024).decode()if data =="##":breakprint(data)else:print(data)if __name__ =="__main__":main()

Insert dictionary

import pymysql 
import re
f =open('dict.txt')
db = pymysql.connect\
(' localhost','root','123456','dict')
cursor = db.cursor()for line in f:try:
l = re.split("[ ]+",line)
except:
pass 
sql ="insert into words (word,interpret)\
values ('%s','%s')"%(l[0],' '.join(l[1:]))try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
f.close()

The above is the whole content of this article, I hope it will be helpful to everyone's study.

Recommended Posts

Python implements electronic dictionary
Python implements Super Mario
Python implements tic-tac-toe game
Python implements man-machine gobang
Python implements Tetris game
Python implements image stitching
Python implements minesweeper game
Python implements scanning tools
Python implements threshold regression
Python implements minesweeper games
Python implements guessing game
Python implements simple tank battle
Python implements udp chat window
Python implements WeChat airplane game
Python implements word guessing game
Python implements a guessing game
Python implements parking management system
Python numpy implements rolling case
OpenCV Python implements puzzle games
Python implements simple tic-tac-toe game
Python implements password strength verification
Python implements car management system
Python implements code block folding
Python implements SMTP mail sending
Python implements multi-dimensional array sorting
How Python implements FTP function
Python implements mean-shift clustering algorithm
Python implements verification code recognition
Python implements gradient descent method
Python implements text version minesweeper
Python implements image stitching function
Python implements the brick-and-mortar game
How Python implements the mail function
Python3 implements the singleton design pattern
Python implements string and number splicing
Python implements ten classic sorting algorithms
Python implements a universal web framework
Python implements 126 mailboxes to send mail
Detailed usage of dictionary in Python
Python implements AI face change function
Python implements the steepest descent method
Python implements the actual banking system
Python implements digital bomb game program
Python implements ftp file transfer function
Python implements username and password verification
How Python implements the timer function
Python implements the aircraft war project
Python implements horizontal stitching of pictures
Python implements GIF graph upside down
Python implements QQ mailbox to send mail
Python implements alternate execution of two threads
Python implements the sum of fractional sequences
python implements the gradient method python the fastest descent method
Python implements singly linked lists and dictionaries
How to sort a dictionary in python
python3 simply implements the combined design pattern
Python implements AI automatic version greedy snake
Python implements image outer boundary tracking operation