Python使用?TCP協(xié)議實(shí)現(xiàn)智能聊天機(jī)器人功能
編寫聊天程序的服務(wù)端代碼和客戶端代碼。完成后,先啟動(dòng)服務(wù)端代碼,然 后啟動(dòng)客戶端程序輸人問題,服務(wù)端可以返回相應(yīng)的答案。要求服務(wù)端代碼具 有一定的智能,能夠根據(jù)不完整的問題識(shí)別客戶端真正要問的問題。 程序運(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()
測(cè)試用例:
how are you
how old are you
what's your name
bye

到此這篇關(guān)于Python 使用 TCP 實(shí)現(xiàn)智能聊天機(jī)器人的文章就介紹到這了,更多相關(guān)Python智能聊天機(jī)器人內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python連接數(shù)據(jù)庫進(jìn)行數(shù)據(jù)查詢的操作代碼
這篇文章主要介紹了Python連接數(shù)據(jù)庫進(jìn)行數(shù)據(jù)查詢的操作代碼,本文給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-06-06
Python中的HTTP請(qǐng)求庫Requests的具體使用
Python作為一種功能強(qiáng)大且易于學(xué)習(xí)的編程語言,提供了許多用于處理HTTP請(qǐng)求的庫,其中,Requests庫是最受歡迎的選擇之一,本文主要介紹了Python中的HTTP請(qǐng)求庫Requests的具體使用,感興趣的可以了解一下2023-12-12
學(xué)點(diǎn)簡單的Django之第一個(gè)Django程序的實(shí)現(xiàn)
這篇文章主要介紹了學(xué)點(diǎn)簡單的Django之第一個(gè)Django程序的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02
pyinstaller打包django項(xiàng)目的實(shí)現(xiàn)步驟
本文主要介紹了pyinstaller打包django項(xiàng)目的實(shí)現(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09

