python生成器------迷你聊天机器人

迷你聊天机器人

迷你聊天机器人实现原理,就是协程。首先,写一个死循环,在里面写许多条件判断。对于每次输入的内容,在循环程序中的条件判断中查找关键字,如果出现,就返回提前设定的值。如果想要退出的话,可以用关键字break退出。代码如下:


def chat_robot():
    res = ''
    while True:
        receive = yield
        if 'age' in receive:
            res = "18"
        elif 'name' in receive:
            res = "小冰"
        elif 'hello' in receive:
            res = 'hello'
        else:
            res = "i dont know"
        print("Robot>>:%s" %(res))

def main():
    Robot = chat_robot()
    next(Robot)
    while True:
        send_data = input("A>>:")
        if send_data == 'q' or send_data == 'bye':
            print("不聊了")
            break
        Robot.send(send_data)


main()


猜你喜欢

转载自blog.csdn.net/qq_41891803/article/details/82151320