Search list of keywords in text and display number of occurrences and which keywords were detected

Viewed 30

I'm using Google's speech-to-text service. From the transcription result, I would like to verify if one or more of my keywords are present in the transcribed text and which keywords are found. For example, given this list:

keywords = ['i mean', 'basically', 'you know' ]

In the sentence below there are two occurrences of keywords:

I mean she looks exactly like Marie. Vivien was right, you know?

What I managed to do so far is to display "success" when a keyword is found but what I would like is for all the words in the keyword list to be searched for in the transcription result, displaying exactly the number of occurrences and which keywords were detected. Using the example above, it should display '2 keywords found: i mean; you know'. Note: uppercase and lowercase don't matter.

Current code:

response_standard_wav = speech_client.recognize(
    config=config_wav,
    audio=audio_wav
)

for i, result in enumerate(response_standard_wav.results):
    alternative = result.alternatives[0]
    print("-" * 20)
    print("First alternative of result {}".format(i))
    print("Transcript: {}".format(alternative.transcript))
    if 'I mean' in format(alternative.transcript):
        print('success')

Current output:

--------------------
First alternative of result 0
Transcript: I mean she looks exactly like Marie. Vivien was right, you know?
success
2 Answers

I hope I understood your question correctly, you want the number of occurrences of each keyword in the transcripted message, along with which keyword was it. The code below does that.

message = "I mean she looks exactly like Marie. Vivien was right, you know?"
keywords = ['I mean', 'basically', 'you know']

for keyword in keywords:
    if keyword in message:
        print(f"{keyword}: {message.count(keyword)}")

Output:
I mean: 1
you know: 1

You can use filter():

text = 'I mean she looks exactly like Marie. Vivien was right, you know?'.lower()
keywords = ['i mean', 'basically', 'you know']
out = list(filter(lambda x: x.lower() in text, keywords))
print(f'{len(out)} keywords found: {"; ".join(out)}')
2 keywords found: i mean; you know
Related