How to format sentences with punctuations in pig latin python

Viewed 46

As the title says, we have to format sentences into pig latin and have the punctuations considered. I am struggling to get it working.

What I've done so far:

user_input = input('Enter a Sentence: ').lower()
words = user_input.split()
vowels = ['a', 'e', 'i', 'o', 'u']

for x, word in enumerate(words):
if word[0] in vowels:
    words[x] = words[x]+ "way"

else:
    has_vowel = False
    
    for y, letter in enumerate(word):
        if letter in vowels:
            words[x] = word[y:] + word[:y] + "ay"
            has_vowel = True
            break
    if(has_vowel == False):
        words[x] = words[x]+ "ay"

pig_latin = ' '.join(words)
print("Pig Latin: ",pig_latin)

desired output:

IN: egg!
OUT: eggway!

output I get:

IN: egg!
OUT: egg!way

What I've tried to do:

# Add a list of punctuations
punct_list = ["!", "(", ")", "[", "]", "{", "}", ";", ":", "'", '"', "?", "/", "\\", "*", "<", ">", "-", "@", "^", "&", "_", ",", "~", "#", "%", ".", "$", "`"]

# Add an elif
elif word[-1] in punct_list:
    words[x] = words[x:-1] + "way" + words[-1]

However, this returns an error that a "str" and "list" could not be concatenated. I am lost, also, I do believe we are not allowed to use any modules. Any help would be appreciated.

1 Answers

I managed to solve your problem using built in re module

The main idea of main function is to split sentence on words, make each word pigified and to substitute initial words on pigified one

import re


def main():
    sentence = 'pig latin, eat banana! will butler?'

    for word in re.findall(r'\w+', sentence):
        pig_word = pigify(word)
        sentence = re.sub(word, pig_word, sentence)

    return sentence


def pigify(word):
    result = ''
    if word[0] in ['a', 'e', 'i', 'o', 'u']:
        result = word+'way'
    else:
        result = word[1:]+word[0]+'ay'
    return result


if __name__ == "__main__":
    x = main()
    print(x)

NOTE: You can rewrite pigify function if you are not satisfied with my algorithm

Related