聊天机器人

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

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()

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、Rasa Rasa是一个开源机器学习框架,用于构建上下文AI助手和聊天机器人。Rasa有两个主要模块: Ras...
    风玲儿阅读 52,549评论 1 30
  • 1. 聊天机器人的发展历史 聊天机器人,是一种通过自然语言模拟人类,进而与人进行对话的程序。 1.1 聊天机器人溯...
    魏鹏飞阅读 4,436评论 0 4
  • 風立_6719阅读 156评论 0 0
  • 无论生活在古代还是现代 杀人放火的事人们永远不会懈怠 不止是为了名利二字 还为了漂亮的姑娘住在隔壁 宽阔的街道高耸...
    莫五四大叔阅读 274评论 0 0
  • 一个行业干久了,局没有当初的激情了,感觉有点疲惫,其中的缘由到底是什么呢?我得好好想想了。 一、上半年总结 每一次...
    腻腻_594f阅读 568评论 0 0