我正在编写Python代码来接收一些音频文件,并在找到“开始”时删除其中的某些部分。当在文本变量中找到“begin”一词时,代码应删除左侧的所有文本。
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:
# listen for the data (load audio to memory)
audio_data = r.record(source)
text = r.recognize_google(audio_data).lower()
words = text.split()
b = 0
for word in words:
b +=1
if word == 'begin':
text = text[:-b]
print(b)
print(text)
我尝试给它一个文本文件,中间有“开始”一词。我本来期望得到一个修剪后的结果,但我没有。
如果我理解正确的话,关键字
begin
表示它后面的所有内容都是你想要保留的内容。我会使用正则表达式替换来表达这一点:
text = r.recognize_google(audio_data).lower()
text = re.sub(r'.*?\bbegin\b\s*', '', text)