人机交互程序 python实现人机对话

yipeiwu_com5年前Python基础

自己随便写了一个人机交互的程序。不存在任何智能,只是可以识别姓名,可以记录对话内容,并保存等到下一次交互时加载。 (推荐面向对象版本)

# hello.py 
# 这是老早写的。不过今天加入了Pickle,然后润色了一下。 
# 可能有点无聊(不推荐使用) 
 
import pickle 
import os.path 
 
def search(x, data): 
  for k, d in enumerate(data): 
    if x == d['name']: 
      return k, d 
 
def save_data(A,pklname): 
  with open(pklname, 'wb') as pkl: 
    pickle.dump(A, pkl) 
 
def load_data(pklname): 
  with open(pklname, 'rb') as pkl: 
    return pickle.load(pkl) 
 
# communicating with computer 
data=[] if not os.path.isfile('data') else load_data('data') 
 
while True: 
  print('Welcome! [type "quit" if you want to quit.]') 
  name=input('--What is your name?\n--') 
  if name in {'quit','Quit','q','Q'}: 
    print('[You quit]') 
    break 
  if not search(name, data): 
    print('--Welcome, '+name+ '. I will remember you name.') 
    d={'name':name,'age':0,'history':[]} 
    data.append(d) 
  else: 
    print('--Hi, '+name+'. How I miss you.') 
 
  k, d=search(name, data) 
  while d['age']==0: 
    age=input('--How old are you?[I will repeat until you respond!]') 
    try: 
      if int(age)==0: continue 
      d['age']=int(age); data[k]=d 
    except: 
      pass 
  while True: 
    y=input('--Chan I help you? [yes/no]') 
    while not y:   
      y=input('--Yes or no?') 
    d['history'].append(y); data[k]=d 
    if y in {'no','No','n','N'}: 
      print('--%s.'%y) 
      print('--Bye bye.') 
      break 
    elif y in {'yes','Yes','y','Y'}: 
      print('--%s.'%y) 
      print('I am pleased to serve you.')     
    else: 
      print('I am sorry. I can not understand what you said.') 
      break     
 
# save data 
y=input('--Do you want to save the data? [yes/no]') 
while not y:   
  y=input('--Yes or no?')         
if y in {'no','No','n','N'}: 
  print('--%s. [You say no.]'%y) 
elif y in {'yes','Yes','y','Y'}: 
  print('--%s. [the data is saved in file named "data".]'%y) 
  save_data(data, 'data') 
else: 
  print('I am sorry. I can not understand what you said. data are not saved.') 

下面是hello.py的面向对象编程版本(推荐)

# hello.py 
 
import pickle 
import os.path 
 
def search(x, data): 
  for k, d in enumerate(data): 
    if x == d['name']: 
      return k, d 
 
class Hello: 
  def __init__(self, name='', data=None): 
    self.name = name 
    self.data = data 
 
  def __getstate__(self): 
    return self.data 
 
  def __setstate__(self, data): 
    self.data = data 
 
  def mainloop(self): 
 
    while True: 
      print('Welcome! [type "quit" if you want to quit.]') 
      name=input('--What is your name?\n--') 
      if name in {'quit','Quit','q','Q'}: 
        print('[You quit]') 
        break 
      if not search(name, self.data): 
        print('--Welcome, '+name+ '. I will remember you name.') 
        d={'name':name,'age':0,'history':[]} 
        self.data.append(d) 
      else: 
        print('--Hi, '+name+'. How I miss you.') 
 
      k, d=search(name, self.data) 
      while d['age']==0: 
        age=input('--How old are you?[I will repeat until you respond!]') 
        try: 
          if int(age)==0: continue 
          d['age']=int(age); self.data[k]=d 
        except: 
          pass 
      while True: 
        y=input('--Chan I help you? [yes/no]') 
        while not y: 
          y=input('--Yes or no?') 
        d['history'].append(y); self.data[k]=d 
        if y in {'no','No','n','N'}: 
          print('--%s.'%y) 
          print('--Bye bye.') 
          break 
        elif y in {'yes','Yes','y','Y'}: 
          print('--%s.'%y) 
          print('I am pleased to serve you.') 
        else: 
          print('I am sorry. I can not understand what you said.') 
          break 
 
    # save data 
    y=input('--Do you want to save the data? [yes/no]') 
    while not y: 
      y=input('--Yes or no?') 
    if y in {'no','No','n','N'}: 
      print('--%s. [You say no.]'%y) 
    elif y in {'yes','Yes','y','Y'}: 
      print('--%s. [the data is saved in file named "data.pkl".]'%y) 
      with open('data.pkl', 'wb') as fo: 
        pickle.dump(self, fo) 
    else: 
      print('I am sorry. I can not understand what you said. data are not saved.') 
    # communicating with computer 
 
 
try: 
  with open('data.pkl', 'rb') as fo: 
    hello=pickle.load(fo) 
except: 
  hello=Hello('ai',[]) 
 
hello.mainloop() 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

django中账号密码验证登陆功能的实现方法

django中账号密码验证登陆功能的实现方法

今天分享一下django的账号密码登陆,前端发送ajax请求,将用户名和密码信息发送到后端处理,后端将前端发送过来的数据跟数据库进行过滤匹配,成功就跳转指定页面,否则就把相对应的错误信息...

Python实现生成密码字典的方法示例

本文实例讲述了Python实现生成密码字典的方法。分享给大家供大家参考,具体如下: key_data.py 文件存放组成数据,可以随时扩充及简化。 #coding=utf-8 #!/...

python selenium 获取标签的属性值、内容、状态方法

获取标签内容 使用element.attribute()方法获取dom元素的内容,如: dr = driver.find_element_by_id('tooltip') dr.ge...

selenium+python 对输入框的输入处理方法

最近自己在做项目的自动化测试(公司无此要求),在用户管理模块做修改用户信息时,脚本已经跑成功,并且的确做了update操作,但是自己登陆页面检查,信息却没有被修改,再次确定系统该模块的编...

Python实现的列表排序、反转操作示例

本文实例讲述了Python实现的列表排序、反转操作。分享给大家供大家参考,具体如下: 排序: 使用sorted方法和列表的sort方法: sorted方法适用范围更广,sort方法只有...