Python音频转文本后保留'begin'右侧内容的代码调试问题
问题分析与修复
原代码的核心问题有两个:
- 用单词计数
b做字符裁剪完全错误,每个单词长度不同,text[:-b]是砍掉文本末尾的b个字符,和你要保留begin及右侧内容的需求完全相反 - 遍历逻辑混乱,找到
begin后未停止循环,后续b的累加会打乱最终裁剪结果
修复后的代码
方案1:基于单词列表处理(更可靠,避免歧义匹配)
import speech_recognition as sr import openai from gtts import gTTS import os import pygame filename = "Recording.wav" r = sr.Recognizer() language = 'en' with sr.AudioFile(filename) as source: audio_data = r.record(source) text = r.recognize_google(audio_data).lower() words = text.split() # 定位第一个'begin'的位置 for idx, word in enumerate(words): if word == 'begin': # 保留begin及右侧所有单词,重新拼接成文本 text = ' '.join(words[idx:]) break # 找到目标后立即停止遍历 else: # 未找到begin时,保持原文本不变 pass print(text)
方案2:直接在原文本中匹配(保留原始格式)
import speech_recognition as sr import openai from gtts import gTTS import os import pygame filename = "Recording.wav" r = sr.Recognizer() language = 'en' with sr.AudioFile(filename) as source: audio_data = r.record(source) text = r.recognize_google(audio_data).lower() # 查找第一个'begin'的起始位置 begin_pos = text.find('begin') if begin_pos != -1: # 从begin的位置开始截取后续所有内容 text = text[begin_pos:] print(text)
补充说明
- 方案1通过拆分单词列表定位
begin,能避免类似beginning这类包含begin的单词被误匹配 - 方案2直接操作原字符串,适合需要保留语音识别原始空格、标点格式的场景
- 如果需要保留最后一个
begin及右侧内容,方案1改成反向遍历即可,方案2用rfind替代find
内容的提问来源于stack exchange,提问作者Mohamad Bdeir
相关产品推荐
相关产品推荐

