Python语音识别:'module'对象没有属性'microphone'

Python Speech Recognition: 'module' object has no attribute 'microphone'

运行 以下代码在 64 位 macbook air 上,在 python 2.7 和 python 3.4

上测试代码
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 LookupError:
    print("Could not understand audio")

当我尝试 python 2.7 时,我不断收到以下错误:

Traceback (most recent call last):
File "star.py", line 3, in <module>
with sr.microphone() as source:
AttributeError: 'module' object has no attribute 'microphone'

(star.py 是我正在测试的文件的名称) 当我尝试 python 3.4 时,我不断收到错误:

Traceback (most recent call last):
File "star.py", line 1, in <module>
import speech_recognition as sr
ImportError: No module named 'speech_recognition'

我已经下载了 speech_recognition 和 pyaudio 库,但我仍然不知道错误的原因。请帮忙!

对于 2.7:PyPI SpeechRecognition page 提到 Microphone 而不是 microphone。尝试将名称大写。如果你试过

>>> import speech_recognition as sr
>>> dir(sr)

看看模块有哪些属性,你可能已经发现了错误。

对于 3.4,我怀疑您只为 2.7 下载并安装了 sr 模块。在命令行(使用 Windows 版本,根据需要调整另一个 OS)

.../python34/Scripts> pip 安装 SpeechRecognition

应该为 3.4 安装。

您需要安装 packadge "pyaudio"

If you want to use audio input from microphones, PyAudio is also necessary. If not installed, the library will still work, but Microphone will not be defined.

Source

找到修复 -

pip install SpeechRecognition

pip install pyaudio

如果您发现错误 -

sudo apt-get install python-pyaudio

sudo apt-get install libjack-jackd2-dev portaudio19-dev

再一次 -

pip install pyaudio

要解决此问题,请尝试打开终端并执行:

brew install portaudio
pip install pyaudio

我希望这对你有用 ;)

Mac 附带 Apple 预装的 Python 2.7。它的默认路径是 /usr/bin/python 但如果你安装 python 3 然后它使用不同的路径 /applications/python 3 (取决于最新版本 3.4 3.5 ..)所以你必须安装 pyaudio 和python 3 个单独的点

打开终端执行:

cd /Applications/Python\ 3.5 
pip3 install SpeechRecognition
pip3 install pyaudio