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