learningpython/pigLatin.py

62 lines
1.7 KiB
Python
Executable file

#! /usr/bin/env python3
import sys
if len(sys.argv)<2:
print('usage: piglatin [text] -translate text to piglatin')
sys.exit()
message = sys.argv[1]
def translateToPigLatin(message):
vowels=('a', 'e', 'i', 'o', 'u', 'y')
piglatin=[] #list of the words
for word in message.split():
#seperate the non-letters at the start of the word
prefixNonLetters = ''
while len(word) > 0 and not word[0].isalpha():
prefixNonLetters += word[0]
word = word[1:]
if len (word) == 0:
piglatin.append(prefixNonLetters)
continue
suffixNonLetters = ''
while len(word)>0 and not word[-1].isalpha():
suffixNonLetters = word[-1]+suffixNonLetters
word = word[:-1]
#remember if word was in uppercase or title case.
wasUpper = word.isupper()
wasTitle = word.istitle()
#make word lowercase for translation.
word = word.lower()
#seperate the consanants at the end of the word.
prefixConsonants = ''
while len(word) > 0 and not word[0] in vowels:
prefixConsonants += word[0]
word = word[1:]
#add pig latin ending
if prefixConsonants == '':
word += 'yay'
else:
word += prefixConsonants+'ay'
#set the word back to upercase or titlecase.
if wasUpper:
word=word.upper()
if wasTitle:
word = word.title()
#add non letters back.
piglatin.append(prefixNonLetters + word + suffixNonLetters)
#join all the words back into a string.
return' '.join(piglatin)
print(translateToPigLatin(message)