Advertisement
asweigart

piglat.py

Jun 2nd, 2019
334
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1. # English to Pig Latin
  2. print('Enter the English message to translate into pig latin:')
  3. message = input()
  4.  
  5. VOWELS = ('a', 'e', 'i', 'o', 'u', 'y')
  6.  
  7. pigLatin = [] # A list of the words in pig latin.
  8. for word in message.split():
  9.     # Separate the non-letters at the start of this word:
  10.     prefixNonLetters = ''
  11.     while len(word) > 0 and not word[0].isalpha():
  12.         prefixNonLetters += word[0]
  13.         word = word[1:]
  14.     if len(word) == 0:
  15.         pigLatin.append(prefixNonLetters)
  16.         continue
  17.  
  18.     # Separate the non-letters at the end of this word:
  19.     suffixNonLetters = ''
  20.     while not word[-1].isalpha():
  21.         suffixNonLetters += word[-1]
  22.         word = word[:-1]
  23.  
  24.     # Remember if the word was in uppercase or titlecase.
  25.     wasUpper = word.isupper()
  26.     wasTitle = word.istitle()
  27.  
  28.     word = word.lower() # Make the word lowercase for translation.
  29.  
  30.     # Separate the consonants at the start of this word:
  31.     prefixConsonants = ''
  32.     while len(word) > 0 and not word[0] in VOWELS:
  33.         prefixConsonants += word[0]
  34.         word = word[1:]
  35.  
  36.     # Add the pig latin ending to the word:
  37.     if prefixConsonants != '':
  38.         word += prefixConsonants + 'ay'
  39.     else:
  40.         word += 'yay'
  41.  
  42.     # Set the word back to uppercase or titlecase:
  43.     if wasUpper:
  44.         word = word.upper()
  45.     if wasTitle:
  46.         word = word.title()
  47.  
  48.     # Add the non-letters back to the start or end of the word.
  49.     pigLatin.append(prefixNonLetters + word + suffixNonLetters)
  50.  
  51. # Join all the words back together into a single string:
  52. print(' '.join(pigLatin))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement