網(wǎng)站首頁 編程語言 正文
編寫聊天程序的服務(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
原文鏈接:https://blog.csdn.net/m0_53354306/article/details/124651191
相關(guān)推薦
- 2022-01-03 antd獲取表單的所有數(shù)據(jù)
- 2022-08-17 R語言ggplot2拼圖包patchwork安裝使用_R語言
- 2022-03-30 Android中圖片占用內(nèi)存的深入分析_Android
- 2022-05-03 如何利用Python實(shí)現(xiàn)簡(jiǎn)易的音頻播放器_python
- 2022-07-08 教你利用python的matplotlib(pyplot)繪制折線圖和柱狀圖_python
- 2022-09-07 Jquery實(shí)現(xiàn)異步上傳文件_jquery
- 2022-09-26 Python?Celery定時(shí)任務(wù)詳細(xì)講解_python
- 2022-06-10 在vscode中快速新建html文件的2種方法總結(jié)_C 語言
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支