Pyglatin Translator


So I’ve just completed the lesson on how to make a pyglatin translator, though when experimenting with it I noticed that I couldn’t make full sentences of English word translate into pig latin. So my question is if I were to modify my polyglactin code, how would I do so if the raw input entered by the user was a full sentence instead of a word to be translated into pig latin???


Let’s see what we know about the problem, and how to solve it bit by bit. We know that a sentence is made of space separated words, which makes it iterable once we break out the words. We know how to translate to PygLatin. We know how to loop. We know about data structures and some of their methods, such as 'str.join(list)`. All in all we have enough information to approach the problem.

  1. split() the sentence into a list of words.
  2. Create an empty list as an alternate.
  3. Iterate over the list of words and add the translation to the alternate list.
  4. Join the list back into a string.

Nobody would expect you to understand this just now…

string = "The rain in Spain falls mainly in the plains"
print (' '.join([x[1:] + x[0] + 'ay' for x in string.split()]))
# heTay ainray niay painSay allsfay ainlymay niay hetay lainspay

As you will soon learn, we can make this code re-usable so that our program may call upon it at an instant, repeatedly. That is where functions show their usefullness.

def pyg_latin_translate(s):
    return ' '.join([x[1:] + x[0] + 'ay' for x in s.split()])

The above print statement would now be reduced to,

print (pyg_latin_translate(string))
# heTay ainray niay painSay allsfay ainlymay niay hetay lainspay

And, we could continue to thrust strings upon the function until our heart’s content, or whatever program value we can derive, accordingly.

The above doesn’t care about length. Empty is accepted. As are non-alpha. They all slip through. We can deal with them in due course.

string = ""
print (pyg_latin_translate(string) if string else 'empty')
# empty


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.