Translating Pig Latin into English Using Python 3

aidandeno picture aidandeno · Mar 31, 2014 · Viewed 12k times · Source

As you will see in my code below, I have already made a program that translates from English into Pig Latin. It follows two rules:

  • If the word begins with a vowel, "way" should be appended (example: apple becomes appleway)
  • If the word begins with a sequence of consonants, this sequence should be moved to the end, prefixed with "a" and followed by "ay" (example: please becomes easeaplay)

I know this is an odd way to do it, but just humour me.

The issue: when translating into English, I can't think of a way to let the code know at exactly which point it should separate the root of the original word from the suffix because some words begin with 1 consonant, others with 2 consonants, etc.

Any help would be appreciated. Please bear in mind that I am a novice.

vowels = ('AEIOUaeiou')

def toPigLatin(s):
    sentence = s.split(" ")
    latin = ""
    for word in sentence:
        if word[0] in vowels:
            latin += word + "way" + " "
        else:
            vowel_index = 0
            for letter in word:
                if letter not in vowels: 
                    vowel_index += 1
                    continue
                else: 
                    break
            latin += word[vowel_index:] + "a" + word[:vowel_index] + "ay" + " "
    return latin[:len(latin) - 1]

def toEnglish(s):
    sentence = s.split(" ")
    english = ""
    for word in sentence:
        if word[:len(word) - 4:-1] == 'yaw':
            english += word[:len(word) - 3] + " "
        else: 
            #here's where I'm stuck
    return english

Thanks in advance!

Answer

Schickmeister picture Schickmeister · Mar 31, 2014

Kevin wis right about completely unambiguous translation being impossible, but I think this is probably what you're looking for:

def toEnglish(s):
    sentence = s.split(" ")
    english = ""
    for word in sentence:
        if word[:len(word) - 4:-1] == 'yaw':
            english += word[:len(word) - 3] + " "
        else: 
            noay = word[:len(word) - 2]
            firstconsonants = noay.split("a")[-1]
            consonantsremoved = noay[:len(noay) - (len(firstconsonants)+1)]
            english += firstconsonants + consonantsremoved + " "
    return english