一聚教程网:一个值得你收藏的教程网站

热门教程

Python使用TCP协议实现智能聊天机器人功能代码示例

时间:2022-06-25 01:14:15 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下Python使用TCP协议实现智能聊天机器人功能代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

编写聊天程序的服务端代码和客户端代码。完成后,先启动服务端代码,然后启动客户端程序输人问题,服务端可以返回相应的答案。要求服务端代码具 有一定的智能,能够根据不完整的问题识别客户端真正要问的问题。程序运行后界面如下图所示。

源代码:
服务端 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

热门栏目