# Notes from Wednesday, October 11

import string

# translates phrases typed in by the user into Pig Latin
def pig():
    phrase = raw_input("Enter a phrase: ")        
    while phrase not in ['bye', 'goodbye', 'quit']:
        print translate(phrase)
        phrase = raw_input("Enter a phrase: ")
    print "Goodbye!"

# translates an entire text file into Pig Latin, line by line
def pig2():
    filename = raw_input("File to translate into Pig Latin: ")
    f = open(filename)
    lines = f.readlines()
    f.close()
    for line in lines:
        print translate(line)

# returns the position of the first vowel (a, e, i, o, u) in a word
def firstVowelPos(word):
    for i in range(len(word)):
        if word[i] in "aeiou":
            return i
    return None

# translates a single word into Pig Latin
def translateWord(word):
    # remember whether the word is capitalized
    if word[0] in string.uppercase:
        isCapitalized = True
    else:
        isCapitalized = False
    # strip off the ending punctuation character, if any
    if word[-1] in string.punctuation:
        punct = word[-1]
        word = word[:-1]
    else:
        punct = ""
    # convert the word to Pig Latin
    word = string.lower(word)
    pos = firstVowelPos(word)
    if pos == None:
        newWord = word + "ay"
    elif pos == 0:
        newWord = word + "way"
    else:
        head = word[:pos]
        tail = word[pos:]
        newWord = tail + head + "ay"
    # add the punctuation back on to the end of the word
    newWord = newWord + punct
    # re-capitalize the word if necessary
    if isCapitalized:
        return string.capitalize(newWord)
    else:
        return newWord

# translates a line of text into Pig Latin
def translate(phrase):
    newWords = []
    for word in string.split(phrase):
        tword = translateWord(word)
        newWords.append(tword)
    newPhrase = string.join(newWords)
    return newPhrase

# Example:
#
# >>> translate("The rain in Spain stays mainly in the plain!")
# 'Ethay ainray inway Ainspay aysstay ainlymay inway ethay ainplay!'

