美文网首页
聊天机器人

聊天机器人

作者: 思想践行 | 来源:发表于2019-12-21 08:23 被阅读0次

    编程讲究模块化责任分离,目的是提高代码的复用性。通过编写简单对话机器人了解代码从无到有,从糙到精的过程。

    1、对话机器人的基本功能

    • 问名字
    • 问心情
    • 问喜欢的颜色

    2、拍脑袋想代码

    #问名字
    print("What's your name?")
    name = input()
    print(f"Hello,{name}!")
    
    #问心情
    print("How are you today?")
    feeling = input()
    if "good" in feeling.lower():
      print("I'm feeling good too!")
    else:
      print("sorry to hear that.")
    
    #问颜色
    import random
    print("What's your favorite color?")
    FavoriteColor = input()
    Color = ['red','yellow','oringe','blue','purple','black','white']
    print(f"You like {FavoriteColor}, that's a great color. My favorite color is {random.choice(Color)}!")
    

    3、找共性

    • 流程是统一的:输出询问-输入回答-通过输入,输出回应。
    • 每个问题中都有重复性的代码比如input() ,在编程过程中,要尽量把重复的代码整理到同一个基类中复用。

    想要整理出基类的框架,就要先将每一个问题进行封装,把它变成一个类。

    #问名字
    class Hello:                   #定义名为Hello的类
      def run():                   #定义函数run()
        print("What's your name?")   #run()的函数体
        name = input()             
        print(f"Hello,{name}!")
        return                       #run()函数的返回值,这里为空,所以不返回内容,也可以替换为``return None`或者省略掉不写。
    Hello.run()                    #调用并运行Hello内的run()函数_如"问颜色"中调用的random.choice()函数是一样的。
    

    在Python中,定义一个函数要使用def语句,依次写出函数名、括号、括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回。
    —— 廖雪峰的官方网站

    #问心情
    class Feeling:
      def run():
        print("How are you today?")
        feeling = input()
        if "good" in feeling.lower():
          print("I'm feeling good too!")
        else:
          print("sorry to hear that.")
    Feeling.run()
    
    #问颜色
    import random
    class Color:
      def run():
        print("What's your favorite color?")
        FavoriteColor = input()
        Color = ['red','yellow','oringe','blue','purple','black','white']
        print(f"You like {FavoriteColor}, that's a great color. My favorite color is {random.choice(Color)}!")
    Color.run()
    

    4、泛化公共基类

    封装成一个个类之后,我们看看哪些是可以复用的,从而泛化出一个公共的基类。
    主框架是

    class XXX:
      def run():
        pass        #如果想定义一个什么事也不做的空函数,可以用pass语句
    XXX.run()
    

    这部分除了类名称,规则是一样的。定义的函数run()的共性上文有提到。

    class Bot:
      def __init__(self):
        self.q = ""
        self.a = ""
      def _think(self,s):
        return s
      def run(self):
        print(self.q)
        self.a = input()
        print(self._think(self.a))
    
    

    修改子类格式

    class Feeling(Bot):
        def __init__(self):
            self.q = "How are you today?"
        def _think(self,s):
            if "good" in s.lower():
                print("I'm feeling good too!")
            else:
                print("sorry to hear that.")
    Feeling().run()
    

    运行结果多了一个None:


    image.png

    任何函数都是有返回值的,不管写不写return。所以要把`Feeling()._think()中的print改为return


    image.png
    image.png
    写出来变成了这个样子:
    #基类
    class Bot:
      def __init__(self):#Python中,定义函数def 函数名(参数): 缩进写函数主体,return输出返回值。
        self.q = "" #这里有点懵,为什么可以突然出现q和a?
        self.a = ""#方法可以在 self 之后带任意的输入参数,这些输入参数由方法自行使用;self.a 定义了一个实例变量(instance variable),前面说了 self 代表未来被实例化的对象自身,. 表示属于对象的,a 则是这个实例变量的名字,这个方法用传进来的参数 a 来初始化实例变量 self.a,要注意这两个 a 是不一样的;
      def _think(self,s):#函数定义在类里,通常我们称之为方法(method)
        return s
      def run(self):
        print(self.q)
        self.a = input()
        print(self._think(self.a))
    #子类——问名字
    class Hello(Bot): 
      def __init__(self):
        self.q = "What's your name?"
      def _think(self,s):       #有下划线的方法在类外部最好不要调用,可能会更改。
        return f"Hello,{s}!"
    Hello().run()   
    #子类——问心情
    class Feeling(Bot):
        def __init__(self):
            self.q = "How are you today?"
        def _think(self,s):
            if "good" in s.lower():
                return "I'm feeling good too!"
            else:
                return "sorry to hear that."
    Feeling().run()
    #子类——问颜色
    import random
    class Color(Bot):
      def __init__(self):
        self.q = "What's your favorite color?"
        self.a = ""
      def _think(self,s):
        Color = ['red','yellow','oringe','blue','purple','black','white']
        return f"You like {s}, that's a great color. My favorite color is {random.choice(Color)}!"
    Color().run()
    

    关于类变量与实例变量的参考文献

    相关文章

      网友评论

          本文标题:聊天机器人

          本文链接:https://www.haomeiwen.com/subject/yibwnctx.html