Python使用ChatterBot遇AttributeError:'time'无'clock'属性的解决咨询
问题:ChatterBot运行报错
AttributeError: module 'time' has no attribute 'clock' 我使用第三方库chatterbot编写了如下代码:
from chatterbot.trainers import ChatterBotCorpusTrainer import time from time import perf_counter # Import the chatterbot module import chatterbot # Create a ChatBot instance with the name chatbotj = chatterbot.ChatBot('epicurus') # Create an instance of the ChatterBotCorpusTrainer trainer = ChatterBotCorpusTrainer(chatbotj) # Train the chatbot using the Italian corpus trainer.train('chatterbot.corpus.italian') exit_conditions = (":q", "quit", "exit") while True: query = input("> ") if query in exit_conditions: break else: response = chatbotj.get_response(query) print(response)
运行代码时,Visual Studio抛出如下错误:
Message=module 'time' has no attribute 'clock' Source=C:\Users\User\source\repos\PythonApplication5\PythonApplication5\PythonApplication5.py Stack Trace: File "C:\Users\User\source\repos\PythonApplication5\PythonApplication5\PythonApplication5.py", line 9, in <module> (Current frame) chatbotj = chatterbot.ChatBot('epicurus') AttributeError: module 'time' has no attribute 'clock'
我已安装的包如下:
ChatterBot==1.0.4 chatterbot-corpus==1.2.0 click==8.1.7 colorama==0.4.6 joblib==1.3.2 mathparse==0.1.2 nltk==3.8.1 Pint==0.22 pymongo==3.13.0 python-dateutil==2.7.5 pytz==2023.3.post1 PyYAML==3.13 regex==2023.8.8 six==1.16.0 SQLAlchemy==1.2.19 tqdm==4.66.1 typing_extensions==4.7.1
我尝试过使用Python 3.9和3.11版本,也试过Chatterbot 1.0.5,通过--install --no-deps单独安装所有包(因为使用pip install chatterbot --upgrade时遇到问题)。请问问题出在哪里,该如何解决?
解决方案
问题根源
time.clock()方法在Python 3.8版本中被正式移除,而你使用的ChatterBot 1.0.4/1.0.5版本仍在调用这个已废弃的方法,导致在Python 3.9及以上版本运行时触发属性错误。
解决方法
1. 降级Python版本到3.8及以下
- 卸载当前Python 3.9/3.11,安装Python 3.8.x版本
- 切换项目的Python解释器为3.8版本
- 重新安装依赖包:
pip install chatterbot chatterbot-corpus
2. 修改ChatterBot源码替换time.clock()
- 查找到ChatterBot的安装路径:运行
pip show chatterbot,查看输出中的Location字段 - 在该路径下搜索包含
time.clock()的文件(常见于chatterbot/utils.py或逻辑模块文件中) - 将所有
time.clock()调用替换为time.perf_counter()(统计总运行时间)或time.process_time()(统计CPU时间,根据上下文选择) - 保存修改后重新运行代码
3. 使用支持Python 3.9+的ChatterBot分支
官方ChatterBot仓库长期未维护,可尝试社区维护的兼容分支:
- 安装开发分支:
pip install git+https://github.com/gunthercox/ChatterBot.git@develop(该分支已修复time.clock兼容问题) - 或直接更换为其他活跃维护的聊天机器人库(如
rasa、基于transformers的对话模型)
内容的提问来源于stack exchange,提问作者mrtx
相关产品推荐
相关产品推荐

