import pickle
data = {"你有女朋友吗":"没有","我们可以交往吗":"可以","今晚约不约":"约","去哪家餐厅":"麦当劳"}
with open("db.pkl",‘wb‘) as f:
f.write(pickle.dumps(data))
with open("db.pkl","rb") as f:
data = pickle.loads(f.read())
class RobotUI:
def __init__(self,name,admin):
self.name = name
self.admin = admin
def talk(self):
worlds = input(‘你说:‘)
if worlds == ‘end‘:
return worlds
else:
reply = backrobot.answer(worlds)
print(f‘{self.name}回答:{reply}‘)
if reply == ‘none‘:
ch = input(‘是否需要增加数据 Y/N:‘)
print(ch)
if ch == ‘Y‘:
updata = input(‘请输入 示例(吃饭了吗:吃了):‘)
new = updata.split(‘:‘)
RobotAdmin.write_data({new[0]:new[1]})
class RobotAdmin:
def __init__(self):
self.data = self.load_data()
def load_data(self):
with open(‘db.pkl‘,‘rb‘) as f:
data = pickle.loads(f.read())
# print(data)
return data
def answer(self,worlds):
if worlds in self.data:
return self.data[worlds]
else:
return ‘none‘
@staticmethod
def write_data(dic):
data.update(dic)
print(data)
with open("db.pkl",‘wb‘) as f:
f.write(pickle.dumps(data))
# robot.talk()
while True:
backrobot = RobotAdmin()
robot = RobotUI(‘robot‘,‘back‘)
if robot.talk() == ‘end‘:
print(‘结束‘)
break
robot.talk()
你说:你有女朋友吗
robot回答:没有
你说:我们可以交往吗
robot回答:可以
你说:今晚约不约
robot回答:约
你说:去哪家餐厅
robot回答:麦当劳
你说:今晚去K歌吗
robot回答:none
是否需要增加数据 Y/N:Y
Y
请输入 示例(吃饭了吗:吃了):今晚去K歌吗:去
{‘你有女朋友吗‘: ‘没有‘, ‘我们可以交往吗‘: ‘可以‘, ‘今晚约不约‘: ‘约‘, ‘去哪家餐厅‘: ‘麦当劳‘, ‘今晚去K歌吗‘: ‘去‘}
你说:end
你说:end
结束
原文:http://blog.51cto.com/13587169/2126078