Python在CMD与PyCharm中均无法找到导入模块问题求助
解决ModuleNotFoundError: No module named 'speech_recognition'问题
问题重现
运行以下Python代码时,PyCharm和CMD均提示找不到speech_recognition模块:
import os #import time import speech_recognition from subprocess import call from platform import python_version home = os.path.expanduser("~") from gtts import gTTS from bs4 import BeautifulSoup import pyaudio import PyPDF2 print('Speech Recognition version ' + speech_recognition.__version__) print('Attempting to read Preamble') wav = "C:\Users\Owner\PycharmProjects\Government\Governing_documents\Preamble.wav" recognizer = speech_recognition.Recognizer() preamble = speech_recognition.AudioFile(wav) with preamble as source: audio = recognizer.record(source) type(audio) recognizer.recognize_google(audio)
PyCharm报错:
C:\Users\Owner\PycharmProjects\Speech\venv\Scripts\python.exe C:\Users\Owner\PycharmProjects\Speech\Wav_to_Text.py Traceback (most recent call last): File "C:\Users\Owner\PycharmProjects\Speech\Wav_to_Text.py", line 3, in <module> import speech_recognition ModuleNotFoundError: No module named 'speech_recognition'
CMD报错:
C:\Users\Owner\PycharmProjects\Speech>python Wav_to_Text.py Traceback (most recent call last): File "C:\Users\Owner\PycharmProjects\Speech\Wav_to_Text.py", line 3, in <module> import speech_recognition ModuleNotFoundError: No module named 'speech_recognition'
解决方案
1. 确保包正确安装
注意安装时的包名是SpeechRecognition(首字母大写),导入时用speech_recognition,执行以下命令安装:
python -m pip install SpeechRecognition
验证安装:执行pip show SpeechRecognition,若返回包的版本、路径等信息则安装成功。
2. 匹配Python解释器与安装环境
PyCharm环境:
- 打开
File > Settings > Project: Speech > Python Interpreter - 检查当前选中的解释器路径(如
C:\Users\Owner\PycharmProjects\Speech\venv\Scripts\python.exe) - 点击
+号,搜索SpeechRecognition并安装到该解释器环境中
- 打开
CMD环境:
- 输入
where python查看当前使用的Python路径 - 若路径是虚拟环境的Python(如
venv\Scripts\python.exe),需先激活虚拟环境:C:\Users\Owner\PycharmProjects\Speech\venv\Scripts\activate - 再执行安装命令,确保包安装到当前Python环境
- 输入
3. 修复虚拟环境不一致问题
如果PyCharm用了虚拟环境,CMD运行脚本时必须先激活虚拟环境再执行:
cd C:\Users\Owner\PycharmProjects\Speech venv\Scripts\activate python Wav_to_Text.py
4. 卸载重装修复异常
若上述步骤无效,尝试卸载重装包:
pip uninstall SpeechRecognition python -m pip install --upgrade pip python -m pip install SpeechRecognition
内容的提问来源于stack exchange,提问作者Jim
相关产品推荐
相关产品推荐

