黑马linux简易聊天室代码,简易聊天机器人(示例代码)

data = {‘name‘:‘coop‘,‘how are you‘:‘fine thank you ,and you‘,‘i am fine too‘:‘thanks‘}

def write_data(dic):

data.update(dic) #扩充字典的方法

write_data({‘morning‘:‘morning‘})

print(data)

{‘name‘: ‘coop‘, ‘how are you‘: ‘fine thank you ,and you‘, ‘i am fine too‘: ‘thanks‘, ‘morning‘: ‘morning‘}

#######

import pickle # 序列化

print(data)

with open(‘data.pkl‘,‘wb‘) as f: # data.pkl--> f -->f.write()-->f.close()

f.write(pickle.dumps(data)) # dumps() 压缩

f.close()

{‘name‘: ‘coop‘, ‘how are you‘: ‘fine thank you ,and you‘, ‘i am fine too‘: ‘thanks‘, ‘morning‘: ‘morning‘}

with open(‘data.pkl‘,‘rb‘) as f:

data = pickle.loads(f.read()) # 还原

print(data)

f.close()

{‘name‘: ‘coop‘, ‘how are you‘: ‘fine thank you ,and you‘, ‘i am fine too‘: ‘thanks‘, ‘morning‘: ‘morning‘}

# 开始架构代码

# 第一步,定义好类,chatbot

class RobotUI:

pass

class RobotAdmin:

pass

# 第二部,初步规划方法

class RobotUI:

def __init__(self,name):

self.name = name

def talk(self):

pass

class RobtAdmin:

def __init__(self):

pass

def answer(self,listen):

# TODO something

return

import pickle

class RobotUI:

""""""

def __init__(self, name1, aa):

self.name = name1

self.admin = aa

def talk(self):

self.welcome()

words = input(‘你:‘)

answer = admin.answer(words) # admin是RobotAdmin类的对象

print(f‘{self.name}:{answer}‘)

def welcome(self):

print(f‘hello, I am robot {self.name}‘)

class RobotAdmin:

def __init__(self):

self.data = self.load_data()

def load_data(self):

with open(‘data.pkl‘,‘rb‘) as f:

data = pickle.loads(f.read())

print(data)

return data

def answer(self,listen):

# TODO answer something from the listen

if listen in self.data:

return self.data[listen]

admin = RobotAdmin()

robot = RobotUI(‘coop‘,admin)

print()

robot.talk()

{‘name‘: ‘coop‘, ‘how are you‘: ‘fine thank you ,and you‘, ‘i am fine too‘: ‘thanks‘, ‘morning‘: ‘morning‘}

hello, I am robot coop

你:i am fine too

coop:thanks

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值