编写聊天程序的服务端代码和客户端代码。完成后,先启动服务端代码,然
后启动客户端程序输人问题,服务端可以返回相应的答案。要求服务端代码具
有一定的智能,能够根据不完整的问题识别客户端真正要问的问题。
程序运行后界面如下图所示。
?
?
源代码:
服务端 Sever.py:
from os.path import commonprefix
from posixpath import split
import socket
#建立聊天回复字典
words={'how are you?':'Fine,thank you.',
'how old are you?':'18',
'what is your name?':'xiaoming',
'which subject do you like?':'computer science',
'bye':'Bye'}
s =socket.socket()
s.bind(('127.0.0.1',8000))
s.listen(1)
clientsocket,clientaddress= s.accept()
print('Connection from',clientaddress)
#开始聊天
while True:
data=clientsocket.recv(1024).decode()
if not data:
break
print('Received:',data)
i=0
key=''
for k in words.keys():
data=' '.join(data.split())
if len(commonprefix([k,data]))>len(k)*0.75:
key=k
break
length=len(set(data.split())&set(k.split()))
if length>i:
i=length
key=k
clientsocket.sendall(words.get(key,'Sorry,can\'t find the question').encode())
clientsocket.close()
客户端 Client.py:
import socket
import sys
s =socket.socket()
try:
s.connect(('127.0.0.1',8000))
except Exception as e:
print('Can\'t find the Sever please try again')
sys.exit()
while True:
c=input('Input the content you want to send:')
s.sendall(c.encode())
data=s.recv(1024)
data=data.decode()
print('Received:',data)
if c.lower()=='bye':
break
s.close()
测试用例:
how are you
how old are you
what’s your name
bye
?
|