python英文聊天机器人(亲测可用)
本文参考https://www.cnblogs.com/youcong/p/10462924.html
第一步:
下载所需包
pip install aiml
出现Successfully installed aiml-0.9.2即安装成功
第二步:
编写代码
导入包:
import sys
import os
import aiml
获得语料库目录:
def _get_module_dir(name):
if os.environ.get('show-info', False):
print('module', sys.modules[name])
path = getattr(sys.modules[name], '__file__', None)
if os.environ.get('show-info', False):
print(path)
if not path:
raise AttributeError(f'module {name} has not attribute __file__')
return os.path.dirname(os.path.abspath(path))
创建机器人:
_alice_path = _get_module_dir('aiml') + '\\botdata\\alice'
os.chdir(_alice_path)
_alice = aiml.Kernel()
_alice.learn("startup.xml")
_alice.respond('LOAD ALICE')
定义聊天函数:
def english_chat(message: str):
return _alice.respond(message)
第三步:
如果你按上代码执行,可能看到如下起飞(我已经起飞)
报错信息是说time包不支持clock函数了(我的python是3.8)
解决方案:
找到Kernel.py,我的Kernel.py在
F:\anaconda3\lib\site-packages\aiml下。将第335行
start = time.clock()
改为:
start = time.time()
然后把第356行
print( "done (%.2f seconds)" % (time.clock() - start) )
改为:
print( "done (%.2f seconds)" % (time.time() - start) )
最后附上全部代码:
import sys
import os
import warnings
try:
import aiml
except (AttributeError, ImportError):
print('''If you want to use english chat robot, please update lib aiml's Kernel.py
line 335 "start = time.time()" to:
"start = time.clock()"
and line 356 "print( "done (%.2f seconds)" % (time.clock() - start) )" to:
"print("done (%.2f seconds)" % (time.time() - start))"''')
warnings.warn('aiml module is wrong')
sys.exit(1)
def _get_module_dir(name):
if os.environ.get('show-info', False):
print('module', sys.modules[name])
path = getattr(sys.modules[name], '__file__', None)
if os.environ.get('show-info', False):
print(path)
if not path:
raise AttributeError('module %s has not attribute __file__' % name)
return os.path.dirname(os.path.abspath(path))
_alice_path = _get_module_dir('aiml') + '\\botdata\\alice'
os.chdir(_alice_path)
_alice = aiml.Kernel()
_alice.learn("startup.xml")
_alice.respond('LOAD ALICE')
def english_chat(message: str):
return _alice.respond(message)
if __name__ == '__main__':
while True:
msg = input('Please input, input q to quit: ')
if msg == 'q':
sys.exit(0)
print('Robot:', english_chat(msg))