Python 找到单词时字符串的右侧部分

问题描述 投票:0回答:1

我正在编写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)

我尝试给它一个文本文件,中间有“开始”一词。我本来期望得到一个修剪后的结果,但我没有。

python string trim
1个回答
0
投票

如果我理解正确的话,关键字

begin
表示它后面的所有内容都是你想要保留的内容。我会使用正则表达式替换来表达这一点:

text = r.recognize_google(audio_data).lower()
text = re.sub(r'.*?\bbegin\b\s*', '', text)
© www.soinside.com 2019 - 2024. All rights reserved.