Pig Latin Python Translator - python

I'm making a pig latin translator in python. I'd like to follow the rules of pig latin which state that it is not the first letter, but rather the first sound that moves to the end. As such, a word like "tree" becomes "eetray", and not "reetay". As such, I'd like to make the program detect whether a word has a digraph at the beginning. Here's my code so far:
import twoletterdigraphs
import threeletterdigraphs
pyg = 'ay'
original = input('Enter a word: ')
if len(original) > 0 and original.isalpha():
word = original.lower()
if word[0] + word[1] + word[2] in threeletterdigraphs.threeLetter:
first = word[0] + word[1] + word[2]
new_word = word + first + pyg
new_word = new_word[3:len(new_word)]
print(new_word)
elif word[0] + word[1] in twoletterdigraphs.twoLetter:
first = word[0]+word[1]
new_word = word + first + pyg
new_word = new_word[2:len(new_word)]
print(new_word)
else:
first = word[0]
new_word = word + first + pyg
new_word = new_word[1:len(new_word)]
print(new_word)
else:
print('empty')
twoletterdigraphs and threeletterdigraphs are python files containing nothing but a tuple with a list of digraphs mapped to a variable twoLetter or threeLetter. Here they are:
twoLetter = ["sh" "tr" "ch" "bl" "br" "cl" "cr" "dr" "fl" "fr" "gl" "gr" "pl" "pr" "sc" "sk"
"sl" "sm" "sn" "sp" "st" "sw" "th" "tr" "tw" "wh" "wr"]
and
threeLetter = ["sch" "scr" "shr" "sph" "spl" "spr" "squ" "str" "thr"]
When I run my code, It will only move the first letter to the end, regardless of what word I use. How can this be fixed?

Related

How do I make my code capitalize the first letter of the word that has a capital letter in it? (Pig Latin)

My code so far is:
def to_pig(string):
words = string.split()
for i, word in enumerate(words):
'''
if first letter is a vowel
'''
if word[0] in 'aeiou':
words[i] = words[i]+ "yay"
elif word[0] in 'AEIOU':
words[i] = words[i]+ "yay"
else:
'''
else get vowel position and postfix all the consonants
present before that vowel to the end of the word along with "ay"
'''
has_vowel = False
for j, letter in enumerate(word):
if letter in 'aeiou':
words[i] = word[j:] + word[:j] + "ay"
has_vowel = True
break
#if the word doesn't have any vowel then simply postfix "ay"
if(has_vowel == False):
words[i] = words[i]+ "ay"
pig_latin = ' '.join(words)
return pig_latin
My code right now coverts a string to pig latin string. If a word starts with one or more consonants followed by a vowel, the consonants up to but not including the first vowel are moved to the end of the word and "ay" is added. If a word begins with a vowel, then "yay" is added to the end.
String:
"The rain in Spain stays mainly in the plains"
However, my code returns:
"eThay ainray inyay ainSpay aysstay ainlymay inyay ethay ainsplay"
While it should return:
"Ethay ainray inyay Ainspay aysstay ainlymay inyay ethay ainsplay"
How do I fix my code so that it returns the first letter capital for the word that has a capital letter?
Use any(... isupper()) to check for the presence of a capital letter and str.title() to capitalize the first letter.
>>> words = "eThay ainray inyay ainSpay aysstay ainlymay inyay ethay ainsplay".split()
>>> words = [word.title() if any(c.isupper() for c in word) else word for word in words]
>>> ' '.join(words)
'Ethay ainray inyay Ainspay aysstay ainlymay inyay ethay ainsplay'
A one-line solution would be to check whether the word contains a capital letter. If so, you want to convert the capital letter to a lowercase letter and then capitalize the first letter of that word. You could do that as such. Suppose you have your array of words, then:
words = [i[0].upper() + i[1:].lower() if i.lower() != i else i for i in words]

Pig Latin Python program

I've been working on a Pig Latin program. However, it doesn't seem to be working and I can't figure out why.
user_input = input("Enter word to be translated:")
def translate(user_input):
first = user_input[0]
if first == "a" or "e" or "i" or "o" or "u":
user_input = user_input.lower()
user_input += "way"
return user_input
else:
user_input = user_input.lower()
user_input = user_input[1:]+first+"ay"
return user_input
print(translate(user_input))
On top of that, I was looking to utilize enumerate to find the position of the first vowel, slicing to isolate the first letter of the word and concatenation to form the word. I've read up on how to use it on a couple websites but I can't seem to figure out how to correctly apply it to this program. I think I would have to define Vowels = 'aeiou' before def translate(user_input) right??
You cannot chain if statements like that in Python, you have to do it the long way:
if first == "a" or first == "e" or first == "i" or first == "u":
or shorten it to:
if first in ["a", "e", "i", "u"]:
Here is the solution. I've made a few changes in your code which i will be explaining below.
user_input = input("Enter word to be translated:\n")
#change_1
vowels = ['a','e','i','o','u']
def translate(user_input):
first = user_input[0]
#change_2
if first in vowels:
user_input = user_input.lower()
user_input += "way"
return user_input
else:
user_input = user_input.lower()
#change_3
for letter in user_input:
if letter in vowels:
index_value = user_input.index(letter)
break
#change_4
user_input = user_input[index_value:] +user_input[:index_value]+ "ay"
return user_input
print(translate(user_input))
1) Create a list of vowels.
2) As our friend #zwer mentioned You cannot chain if statements like that in
Python. So
if first in vowels:
3) For every letter in user_input check if that letter is a vowel and if that letter is a vowel then find the index of it's occurrence.
For example take the word 'trash'
Here a is the first vowel and it's index is 2
if letter in vowels:
index_value = user_input.index(letter)
4) According to wikipedia
"all letters before the initial vowel are placed at the end of the word sequence"
For the word 'trash' it would be
user_string = user_input[2:] + user_input[:2]+"ay"
which would be slicing the word from that index to end, merged with letters before that index. And finally an "ay".
'ash' + 'tr' + 'ay'
Hope this helps.
You can define vowels in the outer scope.
vowels = 'a', 'e', 'i', 'o', 'u'
Then anywhere you can use:
if first in vowels:
My Solution covers the below rules:
1. A word is a consecutive sequence of letters (a-z, A-Z) or apostrophes. You may assume that the input to the function will only be a single "word". Examples: Zebra , apple
2. If a word starts with a vowel, the Pig Latin version is the original word with "way" added to the end
3. If a word starts with a consonant, or a series of consecutive consonants, the Pig Latin version transfers ALL consonants up to the first vowel to the end of the word, and adds "ay" to the end.
4. The letter 'y' should be treated as a consonant if it is the first letter of a word, but treated as a vowel otherwise.
5. If the original word is capitalized, the new Pig Latin version of the word should be capitalized in the first letter. If the original capital letter was a consonant, and thus moved, it should not be capitalized once in its new location.
Solution Starts here:
eng_to_pig_latin = {"football": "ootballfay", "Pittsburgh":"Ittsburghpay",
"Apple":"Appleway","oink":"oinkway",
"ontology":"ontologyway","yellow":"ellowyay","yttrium":"iumyttray"}
eng_word = 'yttrium'
vowels = 'aeiou'
def pig_latin(eng_word):
sub,str1 = [],''
first = eng_word[0]
second = eng_word[1]
# Rule 2
if first.lower() in vowels:
piglatin = eng_word +'way'
# Rule 3
elif first.lower() == first and second.lower() in vowels:
piglatin = eng_word[1:]+first+'ay'
elif first.lower()+second.lower() not in vowels:
# Rule 3 & 4
for l in eng_word:
if l not in vowels:
sub.append(l)
else:
str1 = eng_word[eng_word.index(l):]
break
str2 = ''.join(sub)
piglatin = str1+str2+'ay'
else:
# Rule 5
piglatin = eng_word[1:].capitalize()+first.lower()+'ay'
print(f'Test word is {eng_word} and its equivalent piglatin word is
{piglatin}. Comparison with mapping dictionary is
{eng_to_pig_latin[eng_word] == piglatin}')
pig_latin(eng_word)
Note: The dictionary uses is only to cross-check if the results are as expected, which I am doing in the last print statement.
my logic to translate given word in to Pig Latin translation
vowels=['a','e','i','o','u']
def igpay(name):
a_list=list(name)
if a_list[0] in vowels:
print("First letter is a Vowel")
apnd_letters="way"
else:
print("First letter is a Consonant")
a_list.append(a_list[0])
a_list.pop(0)
apnd_letters="ay"
print("Pig transaltion is {0}".format("".join(a_list)+str(apnd_letters)))
Output:
igpay("pig")
First letter is a Consonant
Pig transaltion is igpay
igpay("apple")
First letter is a Vowel
Pig transaltion is appleway
You can do it exactly the same as you are doing it except you will need to change the second line in translate:
if first == "a" or "e" or "i" or "o" or "u":
to:
if first == "a" or first == "e" or first == "i" or first == "o" or first == "u":
or:
if first in 'aeiou':
If you want to be able to use capital letters however, I would recommend changing first to first.lower().
This becomes:
user_input = input("Enter word to be translated:")
def translate(user_input):
first = user_input[0]
if first.lower() in 'aeiou':
user_input = user_input.lower()
user_input += "way"
return user_input
else:
user_input = user_input.lower()
user_input = user_input[1:]+first+"ay"
return user_input
print(translate(user_input))
If you want the code a bit shorter, I have managed to shorten it to:
def translate():
user_input = input('Enter a word or sentence')
for i in range(len(user_input.split())): print(str((user_input.split())[i][1::])+((user_input.split())[i])[0]+'ay', end=' ')
translate()
Here is another two ways to go about it
Method 1:
Using a function that recursively translates words
sentence = str(input('Input Sentence: '))
vowels = 'aeiouAEIOU'
# 1. strip removes whitespace before and after input
# 2. pig_word_latin deals with one word at a time
# 3. join collects all the words into one sentence with spaces
def pig_latin_word(word):
vowelStart = True
#print(word)
if word[0] not in vowels:
vowelStart = False
return pig_latin_word(word[1:] + word[:1])
elif word[0] in vowels and not vowelStart:
return word + 'ay'
elif word[0] in vowels and vowelStart:
return word + 'way'
def pig_latin(sentence):
words: list = sentence.strip().split(' ')
new_words = []
for word in words:
new_words.append(pig_latin_word(word))
print(" ".join(new_words))
pig_latin(sentence)
Method 2:
Using a function that recursively translates sentences by keeping track of spaces
sentence = str(input('Input Sentence: ')).strip()
vowels = 'aeiouAEIOU'
suffix = {}
suffix[True] = 'way'
suffix[False] = 'ay'
def pig_latin(sentence, acc='', cluster='', word=''):
#print('S:'+sentence, 'C:'+cluster, 'W:'+word)
#print('Acc:',acc)
new_word = len(word)==0
vowel_start= len(cluster)==0
#print('NW:',new_word, suffix[vowel_start])
#print('-')
if len(sentence) == 0:
return acc+word+cluster+suffix[vowel_start]
if sentence[0] == ' ':
return pig_latin(sentence[1:], acc+word+cluster+suffix[vowel_start]+' ')
if new_word == True:
if sentence[0] not in vowels:
#print('1---')
return pig_latin(sentence[1:], acc, cluster+sentence[0], '')
elif sentence[0] in vowels and not vowel_start:
#print('2---')
return pig_latin(sentence[1:], acc, cluster, word+sentence[0])
elif sentence[0] in vowels and vowel_start:
#print('3---')
return pig_latin(sentence[1:], acc, '', word+sentence[0])
else:
return pig_latin(sentence[1:], acc, cluster, word+sentence[0])
print(pig_latin(sentence))

How can I create a code that translates a string sentence to Pyglatin? [duplicate]

This question already has answers here:
python pig latin converter
(2 answers)
Closed 6 years ago.
I have a python code to translate a one worded string to pyglatin and is as follows:
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original)>0 and original.isalpha():
word = original.lower()
first = word[0]
rest = word[1:]
new_word = rest+first+pyg
print new_word
However, I'm stumped on how to translate an entire sentence to Pyglatin. The problem I'm working on has these following conditions: for words that begin with consonants, all initial consonants are moved to the end of the word and 'ay' is appended. For words that begin with a vowel, the initial vowel remains, but 'way' is added to the end of the word.
As an example, the string 'How are you today?' would be 'owhay areway uoyay odaytay?'
Read in a sentence. Break it into individual words (split method). Translate each word to Pig Latin. Concatenate the translations.
Does that get you moving?
Try this. Use split and put it into an empty string.
original = raw_input("Enter Sentence: ")
conversion = ""
for word in original.split():
if len(word)>0 and word.isalpha():
word = word.lower()
first = word[0]
rest = word[1:]
pyg = "ay"
pygword = rest+first+pyg
conversion += pygword + " "
print conversion
Here is my try, but if you are not doing it yourself at least try to understand it. (You are free to ask of course)
This has basic ability to deal with special characters like the "?"
def pygword(word):
vowels = 'aeiou'
if word[0] in vowels:
return word + 'way'
else:
while word[0] not in vowels:
word = word[1:]+word[0]
return word + "ay"
def pygsentence(sentence):
final = ''
for word in sentence.lower().split(): #split the sentence
#words should only end in symols in correct grammar
if word[-1] in '.,;:!?':
symbol = word[-1]
word = word[:-1]
else:
symbol = ''
if word.isalpha(): #check if word is alphanumerically
final += pygword(word)+symbol+' '
else:
return "There is a strange thing in one of your words."
return final[:-1] #remove last unecessary space
There may be faster, more robust, simpler, better understandable ways to do this, but this how I would start.
Test yields me:
In[1]: pygsentence("How are you today? I am fine, thank you very much good sir!")
Out[1]: 'owhay areway ouyay odaytay? iway amway inefay, ankthay ouyay eryvay uchmay oodgay irsay!'
Your code does not obey the vowel/consonant rule, so I did my own converter for single words.
Just realized that it won't be able to deal with apastrophes in the middle of words (we don't really have theese in german ;) ) so there is a little task left for you.
edit: I did not know in which order you wanted the consonants apended, since that became not clear from your example. So i made an alternative pygword function:
def pygword2(word):
vowels = 'aeiou'
if word[0] in vowels:
return word + 'way'
else:
startcons = ''
while word[0] not in vowels:
startcons = word[0] +startcons
word = word[1:]
word = word+startcons
return word + "ay"
See the differnece:
In[48]: pygword("street")
Out[48]: 'eetstray'
In[49]: pygword2("street")
Out[49]: 'eetrtsay'

My program works but Codeacademy does not acknowledge

Here is my code for the pig latin translator. It works both on Code academy and in linux terminal.
pyg = 'ay'
new_word = pyg
original = raw_input('Enter a word: ')
if len(original) > 0 and original.isalpha():
original.lower()
word = original
first = original[0]
if first == 'a' or first =='e' or first == 'i' or first =='o' or first == 'u':
print 'vowel'
elif first != 'a' or first !='e' or first !='o' or first !='i' or first !='u':
print word.lower()[1:] + first +new_word
else:
print 'empty'
Code academy gives following result;
Oops, try again! Your word started with a consonant, but “ay' was printed instead of “ogday”. Make sure the correct value #is stored in “new_word”.
"ay" is not printed but "ogday' is printed.
Does anyone know how to fix this? I cannot continue with Codeacademy as without solving this.
You can do something like this for example. You are in the right track just use what you have learned in the Code academy up to this task.
consonants = "bcdfghjklmnpqrstvxz"
original = raw_input('Enter a word: ')
if len(original) > 0 and original.isalpha():
if original.lower()[0] in 'aeiou':
print original.lower() + 'ay'
else:
keep_first_consonants = ''
count = 0
for letter in original.lower():
if letter in consonants:
keep_first_consonants = keep_first_consonants + letter
count += 1
else:
break
total_characters = len(original.lower())
print original.lower()[count:total_characters] + keep_first_consonants + 'ay'
else:
print 'Accept only letters'
The codeacademy lesson checker seems to check the variable new_word when you hit run
So you just need to use new_word for both your print varibles
This code works:
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
if first == "a" or first == "e" or first == "i" or first == "o" or first == "u":
new_word = original + pyg
print new_word
else:
newer_word = word[1:]
new_word = newer_word + first + pyg
print new_word

Confused about order for processes

I'm trying to work on a pig latin type setup. The rule for consonant is to take the first letter of the string, move it to the end and add ay. My problem is that I'm deleting the first letter and moving it to the end...I'm not sure how to do this at the same time. Thank you.
pyg = 'ay'
original = raw_input('Enter a word:')
word = original.`enter code here`lower()
first = original[0]
if len(original) > 0 and original.isalpha():
if first == "a" or "e" or "i" or "o" or "u" or "A" or "E" or "I" or "O" or "U":
print("vowel")
new_word = original.append(pyg)
else:
print("consonant")
new_word = (word.pop[0] and word.append(word[0]) + str(pyg)
print original
else:
print 'empty'
Like this?
new_word = word[1:] + word[0] + pyg

Categories