python英文聊天机器人(亲测可用)

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))
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值