使用Python3+Watson Speech to Text API编写启动项目命令遇阻
实现基于Watson Speech to Text的启动命令逻辑优化
看起来你已经搭好了基础的命令识别框架,现在要完善启动项目的核心逻辑对吧?我来帮你把这块捋得更严谨些,补上关键的启动执行部分。
首先先说说你现有代码可以优化的小细节:Python里判断字符串值相等推荐用==而非is(is是判断对象同一性,对于动态赋值的状态变量来说==更稳妥),另外语音转录的文本可能带空格或大小写差异,匹配时可以更鲁棒一点。
优化后的指令识别与启动逻辑
# 识别启动命令并切换状态 if Command_State == 'Started': # 先提取转录文本,避免重复索引取值 transcript = x[0]['alternatives'][0]['transcript'].strip() # 兼容"run"或"run 项目名"这类指令,忽略大小写 if transcript.lower() == 'run' or transcript.lower().startswith('run '): print("Running the project...") Command_State = 'Run' self.listening = True # 调用启动项目的核心方法 self.launch_target_project()
实现启动项目的核心方法
接下来你需要单独写一个处理项目启动的函数,把具体的启动逻辑放进去,比如启动Flask服务、运行脚本核心函数等:
def launch_target_project(self): """项目启动的核心逻辑,根据你的项目类型修改""" try: # 示例1:如果是Flask Web项目 # from your_project_main import app # app.run(host='0.0.0.0', port=5000, debug=True) # 示例2:如果是脚本式项目,直接执行核心函数 # your_project_core_function() print("Project launched successfully!") except Exception as e: print(f"Launch failed: {str(e)}") # 启动失败后切回初始状态,方便重新触发 Command_State = 'Started'
后续状态的监听处理
当状态切换到'Run'后,你可以在后续的循环监听逻辑里加入状态判断,比如处理停止指令:
# 持续监听的循环逻辑示例 while self.listening: # 这里保持Watson Speech to Text的监听逻辑,获取最新transcript if Command_State == 'Run': current_transcript = x[0]['alternatives'][0]['transcript'].strip() if current_transcript.lower() == 'stop': print("Stopping project...") Command_State = 'Started' # 可选:添加停止项目的逻辑 # self.stop_target_project()
内容的提问来源于stack exchange,提问作者KardasR
相关产品推荐
相关产品推荐

