You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码报错求助:Expected expression与SyntaxError问题排查

问题排查与修正方案

原代码存在的语法错误:

  • for循环语法错误:enumerate:(sr.Microphone.list_microphone_names())里多了个冒号,正确写法是enumerate(...),冒号应该放在整个for循环语句的末尾。
  • 代码块缩进缺失:print语句没有缩进,Python要求循环内的代码必须缩进(通常用4个空格)。
  • format参数错误:index.name是错误用法,enumerate返回的是(索引值, 元素值)的元组,这里应该直接传入index和name两个变量,对应字符串里的{0}和{1}。
  • 字符串引号冲突:你修改后的print语句里,内部双引号没有转义,同时末尾多了一个多余的右括号。

修正后的完整代码:

import speech_recognition as sr

# 遍历系统内所有麦克风设备
for index, name in enumerate(sr.Microphone.list_microphone_names()):
    # 格式化输出设备信息,注意缩进和参数传递
    print('Microphone with name "{1}" found for `Microphone(device_index={0})`'.format(index, name))

更简洁的f-string写法(Python 3.6+支持):

import speech_recognition as sr

for index, name in enumerate(sr.Microphone.list_microphone_names()):
    print(f'Microphone with name "{name}" found for `Microphone(device_index={index})`')

内容的提问来源于stack exchange,提问作者Sin nombre

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 06:43:11