想要用Python來實現與智能機器人對話只需要創建一個服務器端和一個用戶端就可以了,彼此的ip地址一致
首先創建服務器端,這裏是用了線程和socket模塊,
代碼如下:
from socket import *
import threading
#
#問題庫
questionDict ={"蘋果":"一種水果,很好喫", "小姐姐":"是對女孩的一種描述", "豬":"是一種動物", "佩奇":"是一直粉色的豬","你好":"你也好", "我愛你":"我也愛你", "小哥哥":"是對男孩的一種描述", "黃瓜":"是一種蔬菜", "小編":"你最帥", "Python":"我的最愛"}
#智能問答機器人服務器
class RobotServer():
def __init__(self, ip='10.0.14.160', port=8080, connectSize=100):
'''
:param ip 根據自己電腦ip地址或者想要連接某個電腦的ip地址
:param port:服務器端口號
:param connectSize:服務器默認的併發數量
'''
self.__ip = ip
self.__port = port
self.__connectSize = connectSize
pass
def startServer(self):
server = socket(AF_INET, SOCK_STREAM)
server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
server.bind((self.__ip, self.__port))
server.listen(self.__connectSize)
while True:
clientConn, clientAddr = server.accept()
#定義獨立的線程,除了每一個用戶的請求
wt = WorkThread(clientConn, clientAddr) #等待客戶端請求
wt.start()
pass
pass
pass
class WorkThread(threading.Thread):
def __init__(self, connection, addr, bufferSize=8096):
threading.Thread.__init__(self)
self.__connection = connection
self.__addr = addr
self.__bufferSize = bufferSize
pass
def run(self):
receiveMsg = self.__connection.recv(self.__bufferSize)
receiveMsg = receiveMsg.decode("utf-8")
answer = ""
for temp in questionDict.keys():
if temp.count(receiveMsg) > 0:
answer = questionDict[temp]
break
pass
pass
if not answer:
answer = '你說啥'
self.__connection.send(answer.encode("utf-8"))
self.__connection.close()
pass
pass
if __name__ == "__main__":
rs = RobotServer()
rs.startServer()
pass
客戶端代碼如下:
import socket
from socket import *
class RobotClient():
def __init__(self, ip='10.0.14.160', port=8080, bufferSize=8096):
self.__ip = ip
self.__port = port
self.__bufferSize = 8096
pass
def startSendMsg(self, msg):
client = socket(AF_INET, SOCK_STREAM)
client.connect((self.__ip, self.__port))
client.send(msg.encode("utf-8"))
receive = client.recv(self.__bufferSize)
print(receive.decode('utf-8'))
client.close()
pass
pass
if __name__ == '__main__':
rc = RobotClient()
while True:
msg = input("你說我答:")
rc.startSendMsg(msg)
pass
接下來運行結果:
你說我答:你好
你也好
你說我答:我愛你
我也愛你
你說我答:小姐姐
是對女孩的一種描述
你說我答:小哥哥
是對男孩的一種描述
你說我答:小編
你最帥
你說我答: