码迷,mamicode.com
首页 > 其他好文 > 详细

简易聊天机器人

时间:2018-05-25 11:08:03      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:python

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

简易聊天机器人

标签:python

原文地址:http://blog.51cto.com/13118411/2120064

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!