简体   繁体   English

python语音识别中的AttributeError

[英]AttributeError in python speech recognition

import speech_recognition as sr

r = sr.Recognizer()

with sr.Microphone as source:
   print("Say something")
   audio = r.listen(source)
   voice_data = r.recognize_google(audio)
   print(voice_data)

I am trying to compiling this code but it gives error like this :-我正在尝试编译这段代码,但它给出了这样的错误:-

Exception has occurred: AttributeError
__enter__
File "C:\Users\admin\Desktop\text to speech\speech to text.py", line 5, in 
<module>
with sr.Microphone as source:

Every object used in a context manager, should have an __enter__ method and an __exit__ method implemented in its class.上下文管理器中使用的每个对象都应该在其类中实现一个__enter__方法和一个__exit__方法。 The object you are using, sr.Microphone , is an instance of a class that doesn't implement them.您正在使用的对象sr.Microphone是未实现它们的类的实例。 To solve this, you should either not use a context manager (don't use the with ), or implement the __enter__ and __exit__ methods for sr.Microphone 's class.要解决此问题,您不应该使用上下文管理器(不要使用with ),或者为sr.Microphone的类实现__enter____exit__方法。 You can find a detailed explanation about context managers in the Python documentation, or a shorter one here .您可以在 Python 文档中找到有关上下文管理器的详细说明,或在此处找到更简短的说明。

You just need to use sr.Microphone() you've forgot paranthesis.你只需要使用sr.Microphone()你忘记了括号。 Remember microphone is a method.记住麦克风是一种方法。

It looks like you have incorrect intention.看起来您的意图不正确。 Try running after fixing indentaion:修复缩进后尝试运行:

import speech_recognition as sr

r = sr.Recognizer()

with sr.Microphone as source:
  print("Say something")
  audio = r.listen(source)
  voice_data = r.recognize_google(audio)
  print(voice_data)

As @motyzk answered, the context manager should have an enter method and an exit method implemented in its class.正如@motyzk 回答的那样,上下文管理器应该在其类中实现了一个进入方法和一个退出方法。 But I believe sr.Microphone already have it.但我相信 sr.Microphone 已经有了它。 Please check if you have installed all the required libraries请检查您是否已安装所有必需的库

I know this is kind of late, but try using sr.Microphone() instead of sr.Microphone我知道这有点晚了,但尝试使用sr.Microphone()而不是sr.Microphone

>>> import speech_recognition as sr
>>> type(sr.Microphone)
<class 'type'>
>>> type(sr.Microphone())
<class 'speech_recognition.Microphone'>

Here you can see the difference between sr.Microphone() and sr.Microphone , as one is a type, and one is an actual instance of that type.在这里您可以看到sr.Microphone()sr.Microphone之间的区别,因为一个是类型,一个是该类型的实际实例。

The type itself doesn't have methods for use in a context manager, but an instance of the class does.类型本身没有在上下文管理器中使用的方法,但类的实例有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM