欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python使用?TCP協(xié)議實現(xiàn)智能聊天機(jī)器人功能

 更新時間:2022年05月09日 11:50:33   作者:Yvonnae  
TCP協(xié)議適用于對效率要求相對較低而準(zhǔn)確性要求很高的場合,下面通過本文給大家介紹基于Python?使用?TCP?實現(xiàn)智能聊天機(jī)器人,需要的朋友可以參考下

編寫聊天程序的服務(wù)端代碼和客戶端代碼。完成后,先啟動服務(wù)端代碼,然 后啟動客戶端程序輸人問題,服務(wù)端可以返回相應(yīng)的答案。要求服務(wù)端代碼具 有一定的智能,能夠根據(jù)不完整的問題識別客戶端真正要問的問題。 程序運(yùn)行后界面如下圖所示。

源代碼:
服務(wù)端 Sever.py:
from os.path import commonprefix
from posixpath import split
import socket
#建立聊天回復(fù)字典
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

到此這篇關(guān)于Python 使用 TCP 實現(xiàn)智能聊天機(jī)器人的文章就介紹到這了,更多相關(guān)Python智能聊天機(jī)器人內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論