要怎么才能学会Python编程呢?我觉得最好的方法就是“做中学,玩中学”,只有亲自动手去做Python项目,才能学以致用,真正掌握这门编程语言,为我所用。编程玩家俱乐部推出了挑战100+ Python项目,代码和文档开源在:github.com/zhiwehu/100…
来吧,让我们动手做起来!
英语口语学习是很多人都感觉困难的,今天我们就来使用Python编程来进行英语口语练习!
项目需求
- 在命令行窗口运行;
- 程序运行时,会让你输入一句英语,然后你需要对着麦克风读出这句英语;
- 程序会判断你读的对不对,如果不对会让你重读,直到读对为止。
Python编程知识点
- while循环
- 用户输入字符串
- 字符串小写
- 条件判断
- 自定义函数
- 异常处理
- SpeechRecognition 模块 (安装:
pip install SpeechRecognition
) it support these speech recognitions:recognize_bing()
: Microsoft Bing Speechrecognize_google()
: Google Web Speech APIrecognize_google_cloud()
: Google Cloud Speech – 需要安装google-cloud-speech
模块recognize_houndify()
: Houndify by SoundHoundrecognize_ibm()
: IBM Speech to Textrecognize_sphinx()
: CMU Sphinx – 需要安装PocketSphinx
模块recognize_wit()
: Wit.ai
- pyaudio 模块 (安装:
pip install pyaudio
)
参考代码
import speech_recognition as sr
def recognize_speech_from_mic(recognizer, microphone):
'''
麦克风录音并转文字 `microphone`.
:param recognizer: 语音识别器
:param microphone: 麦克风
:return: `None` 如果识别失败返回None,否则返回语音文字
'''
print('开始朗读')
# 录音并去除噪音
with microphone as source:
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
# 调用语音识别,亲测微软bing国内可用,国外建议使用google
try:
text = recognizer.recognize_google(audio)
except Exception as e:
print(e)
text = None
return text
if __name__ == '__main__':
# 输入
text = input('请输入一句英语: ').strip()
# 创建语音识别器和麦克风
recognizer = sr.Recognizer()
microphone = sr.Microphone()
# 录音并获取文字
speech_text = recognize_speech_from_mic(recognizer, microphone)
while speech_text != None and text.lower() != speech_text.lower():
print(speech_text)
speech_text = recognize_speech_from_mic(recognizer, microphone)
if speech_text:
print('{} {}'.format(speech_text, '✓'))
else:
print('语音识别服务暂不可用,请稍后再试。')
复制代码
运行测试
- 使用
pip install requirements.txt
安装模块:pyaudio
andSpeechRecognition
- 运行
python 4.py
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END