convEnglishPigLatin.py

The Problem
MIT OCW 6.189 A Gentle Introduction to Programming Using Python
Lab 6 Problem 2 – Pig-Latin Converter

Write a program that lets the user enter in some English text, then converts the text to Pig-Latin. To review, Pig-Latin takes the first letter of a word, puts it at the en and appends “ay”. The only exception is if the first letter is a vowel, in which case we keep it as is and append “hay” to the end.

E.g. “hello” -> “ellohay”, and “image” -> “imagehay”

It will be useful to define a list or tupple at the top called VOWELS. This way you can check if a letter x is a vowel with the expression x in VOWELS

It’s tricky for us to deal with punctuation and numbers with what we know so far, so instead, ask the user to enter only words and spaces. You can convert their input from a string to a list of strings by calling split on the string:

"My name is John Smith".split(" ")
-> ["My", "name", "is", "John", "Smith"]

Using this list, you can go through each word and convert is to Pig-Latin. Also, to get a word except for the first letter, you can use word[1:].

Hints: It will make your life much easier – and your code much better – if you separate tasks into functions, e.g. have a function that converts one word to Pig-Latin rather than putting it into your main program code.

The Code

VOWELS = ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U")

print "\nEnglish - Pig-Latin Converter v0.1"
print "\nThis program converts English text to Pig-Latin."
print "\nNote: Punctuations and numbers are not yet supported."
print "      Input only letters and spaces."
print "      Uppercase is not yet fully supported."

def conv_consonant_start(word):
 pig_latin_word = word[1:] + word[0] + "ay"
 return pig_latin_word

def conv_vowel_start(word):
 pig_latin_word = word + "hay"
 return pig_latin_word

engl = raw_input("Input the text you would like to convert: ")
engl_words = engl.split(" ")

pig_latin_words = []

for i in engl_words:
 first_letter = i[0]
 vowel = False
 if first_letter in VOWELS:
 vowel = True
 if vowel == True:
 pig_latin_words.append(conv_vowel_start(i))
 else:
 pig_latin_words.append(conv_consonant_start(i))

print "\n\tEnglish:", engl
print "\tPig-Latin:", " ".join(pig_latin_words)

Advertisement
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.