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

源代碼:
服務(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)文章
Python連接數(shù)據(jù)庫進(jìn)行數(shù)據(jù)查詢的操作代碼
這篇文章主要介紹了Python連接數(shù)據(jù)庫進(jìn)行數(shù)據(jù)查詢的操作代碼,本文給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-06-06
學(xué)點簡單的Django之第一個Django程序的實現(xiàn)
這篇文章主要介紹了學(xué)點簡單的Django之第一個Django程序的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02
pyinstaller打包django項目的實現(xiàn)步驟
本文主要介紹了pyinstaller打包django項目的實現(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09

