本文重点演示使用socket实现TCP通信以及字典和集合的用法,客户端发来信息之后,服务端会尽量猜测客户端要表达的真正意思,然后选择合适的内容进行回复。
服务端小机器人代码:
import socket
from os.path import commonprefix
words = {'how are you?':'Fine,thank you.',
'how old are you?':'38',
'what is your name?':'Dong FuGuo',
"what's your name?":'Dong FuGuo',
'where do you work?':'University',
'bye':'Bye'}
HOST = ''
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#绑定socket
s.bind((HOST, PORT))
#开始监听一个客户端连接
s.listen(1)
print('Listening on port:',PORT)
conn, addr = s.accept()
print('Connected by', addr)
#开始聊天
while True:
data = conn.recv(1024).decode()
if not data:
break
print('Received message:', data)
#尽量猜测对方要表达的真正意思
m = 0
key = ''
for k in words.keys():
#删除多余的空白字符
data = ' '.join(data.split())
#与某个“键”非常接近
#就直接返回
if len(commonprefix([k, data])) > len(k)*0.7:
key = k
break
#使用选择法
#选择一个重合度较高的“键”
length = len(set(data.split())&set(k.split()))
if length > m:
m = length
key = k
#选择合适的信息进行回复
conn.sendall(words.get(key, 'Sorry.').encode())
conn.close()
s.close()
客户端代码:
import socket
import sys
#服务端主机IP地址和端口号
HOST = '10.2.1.2'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
#连接服务器
s.connect((HOST, PORT))
except Exception as e:
print('Server not found or not open')
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()
聊天过程截图:
如果觉得《使用Python开发会聊天的智能小机器人》对你有帮助,请点赞、收藏,并留下你的观点哦!