人机交互程序 python实现人机对话
(编辑:jimmy 日期: 2024/11/20 浏览:3 次 )
自己随便写了一个人机交互的程序。不存在任何智能,只是可以识别姓名,可以记录对话内容,并保存等到下一次交互时加载。 (推荐面向对象版本)
# 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"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"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密码错误三次锁定(实例讲解)