Python已安装speech_recognition却无法导入问题求助
先看一下你的代码:
import speech_recognition as sr r = sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source) try: print("You said: " + r.recognize(audio)) except: print("i didn't quite get that")
报错信息:
Traceback (most recent call last):
File "C:\python projects\test.py", line 1, in
import speech_recognition as sr
ModuleNotFoundError: No module named 'speech_recognition'
这种情况大概率是Python环境不一致或者库安装路径不对导致的,给你几个实用的解决步骤:
确认Python解释器与pip的匹配性
很多人遇到“安装了库但找不到”的问题,核心原因是安装库的pip和运行代码的Python不是同一个环境。打开命令行,分别输入:python --version pip --version看两个命令输出的Python版本是否一致。如果不一致,就用
python -m pip install speechrecognition来安装,这个命令会强制使用当前python命令对应的pip,确保库安装到正确的环境里。重新安装正确的包
注意:官方的包名是speechrecognition(没有下划线),虽然导入时用的是speech_recognition,但安装时要写对包名。执行下面的命令重新安装并升级:python -m pip install --upgrade speechrecognition检查虚拟环境是否激活
如果你用了虚拟环境管理项目依赖,一定要先激活对应的虚拟环境再安装库。比如Windows下激活命令是:venv\Scripts\activateLinux/macOS下是:
source venv/bin/activate激活后再安装库,这样库才会被安装到项目的虚拟环境中,运行代码时才能找到。
配置IDE的Python解释器
如果你用VS Code、PyCharm这类IDE,要检查IDE使用的Python解释器是不是安装了speech_recognition的那个。比如:- VS Code:点击左下角的Python版本号,在弹出的列表里选择正确的解释器
- PyCharm:依次打开
File > Settings > Project: 你的项目名 > Python Interpreter,查看列表里是否有speechrecognition,没有的话点击+号搜索安装。
内容的提问来源于stack exchange,提问作者H_raven

