Search code examples
python-3.xlogictext-to-speech

my code works but not exactly as i expect it to


I'm new to all this coding thing and I was writing a program to convert text-to-speech. I have written it and it does work but not as i expected it to work.

Code :

from gtts import gTTS

import time

from pygame import mixer

a = input("Enter shoutout names separated by a comma: ")

a.split(",")

list = []

for i in a:

    list.append(a)

for i in list:

    g = gTTS("Shoutout to "+i,lang="en",tld="com.au")

    speech_file = 'spf.mp3'

    g.save(speech_file)

    mixer.init()

    mixer.music.load('spf.mp3')

    mixer.music.play()

    time.sleep(len(list))

It's python. Say the input was a, b, c and d. Now the following is the output: Shoutout to a, b, c, and d(in computer voice). I was expecting: Shoutout to a Shoutout to b Shoutout to c Shoutout to d`

Can someone smarter than me tell me why that is not happening.


Solution

  • Alright, there are lots of mistakes. Here is the thing... The split() function returns a list. So, you need to put it in a variable. Suppose a = a,b,c,d. When you loop through a, you're looping through a string like:

    a = a,b,c,d 
    [0] = a
    [1] = b
    [2] = c
    [3] = d
    

    You're also appending a to list not looping through the items. So the list in the end is list = ['a,b,c,d', 'a,b,c,d', 'a,b,c,d', 'a,b,c,d', 'a,b,c,d', 'a,b,c,d', 'a,b,c,d'].

    So, In the last loop g = 'a,b,c,d'.

    Wrapping up, I believe it would be something like this:

    from gtts import gTTS
    
    import time
    
    from pygame import mixer
    
    a = input("Enter shoutout names separated by a comma: ")
    
    a_list = a.split(",")
    
    complete_text = ""
    for item in a_list:
        complete_text += f"Shoutout to {item} "
    
    g = gTTS(complete_text, lang="en", tld="com.au")
    speech_file = 'spf.mp3'
    g.save(speech_file)
    mixer.init()
    mixer.music.load('spf.mp3')
    mixer.music.play()
    time.sleep(len(a_list))