As you will see in my code below, I have already made a program that translates from English into Pig Latin. It follows two rules:
If the word begins with a vowel, "way" should be appended (example: apple becomes appleway)
If the word begins with a sequence of consonants, this sequence should be moved to the end, prefixed with "a" and followed by "ay" (example: please becomes easeaplay)
I know this is an odd way to do it, but just humour me.
The issue: when translating into English, I can't think of a way to let the code know at exactly which point it should separate the root of the original word from the suffix because some words begin with 1 consonant, others with 2 consonants, etc.
Any help would be appreciated. Please bear in mind that I am a novice.
vowels = ('AEIOUaeiou')
def toPigLatin(s):
sentence = s.split(" ")
latin = ""
for word in sentence:
if word[0] in vowels:
latin += word + "way" + " "
else:
vowel_index = 0
for letter in word:
if letter not in vowels:
vowel_index += 1
continue
else:
break
latin += word[vowel_index:] + "a" + word[:vowel_index] + "ay" + " "
return latin[:len(latin) - 1]
def toEnglish(s):
sentence = s.split(" ")
english = ""
for word in sentence:
if word[:len(word) - 4:-1] == 'yaw':
english += word[:len(word) - 3] + " "
else:
#here's where I'm stuck
return english
Thanks in advance!
Kevin wis right about completely unambiguous translation being impossible, but I think this is probably what you're looking for:
def toEnglish(s):
sentence = s.split(" ")
english = ""
for word in sentence:
if word[:len(word) - 4:-1] == 'yaw':
english += word[:len(word) - 3] + " "
else:
noay = word[:len(word) - 2]
firstconsonants = noay.split("a")[-1]
consonantsremoved = noay[:len(noay) - (len(firstconsonants)+1)]
english += firstconsonants + consonantsremoved + " "
return english
Although this will not succeed for every pig latin word, as Kevin and ghoti have noted, you can get pretty close by looking for that special 'a' you are adding.
First, get rid of the extra 'ay' at the end, since it will throw off the search for your special 'a':
>>> tmp = word[:-2]
>>> tmp
'easeapl'
Then, use find or index in order to get the location of that special 'a'. Note that it will search from the beginning of the string, so you should reverse the string temporarily:
>>> tmp = tmp[::-1]
>>> tmp
'lpaesae'
>>> ind = tmp.index('a')
>>> ind
2
Now, take the part to the left of that index and the part to the right of that index, reverse each of them, and reassemble. These slices start to get pretty tricky, so bear with me:
>>> prefix = tmp[ind-1::-1]
>>> prefix
'pl'
>>> suffix = tmp[:ind:-1]
>>> suffix
'ease'
>>> english = prefix + suffix
>>> english
'please'
For some more info on slicing, see this great answer.
I do see your problem.
strap -> apstray seems pretty straightforward. But by your rules it might reverse to rapst or traps.
Perhaps one way to do this is to cycle through possibilities until you find a word that matches a word in English. You could make a word list:
with open("/usr/share/dict/words","r") as f:
wordlist = f.read().splitlines()
Then in toEnglish, step back through each iteration of the mutation (add a if word in wordlist: to test each of rapst, traps, etc). and settle on a word if it's in the list.
This method is guaranteed to fail on words like "strap". :-) YMMV.
def toEnglish(s):
sentence = s.split(" ")
english = ""
for word in sentence:
if word[:len(word) - 4:-1] == 'yaw':
english += word[:len(word) - 3] + " "
else:
index = -3
# count consonent between two last a
for letter in reversed(word[:-3]):
if letter is not 'a':
index-=1
else:
break
english += word[index:-2] + word[:index-1] + " "
return english
Should to the trick :)
Well, for me, I just do this:
word = "python"
word = word[1:len(word)] + word[0] + "ay"
Related
So I have a function that takes a string input and turns it into pig latin.
For all words that begin with consonants (everything except vowels), I have to take the first letter of that word and move it to the back and then add "ay" to the word.
For example "like" would become "ikelay".
In my program, the string input given to me is first split and then each element of that newly created list is checked to see if the first character of that element is either a vowel, a consonant, or otherwise.
def simple_pig_latin(input, sep=" ", end="."):
splitinput = input.split(sep)
for i in splitinput:
if splitinput[splitinput.index(i)][0] in ['a','e','i','o','u']:
splitinput[splitinput.index(i)] = str(i) + "way"
elif splitinput[splitinput.index(i)][0] in ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']:
splitinput[splitinput.index(i)] = str(i) + "ay"
else:
continue
finalstring = ' '.join(splitinput)
finalstring = finalstring + end
simple_pig_latin("i like this")
Notice in the elif branch, I am supposed to take the first letter of i and put it at the end of that word and add "ay" to it. Given the input string "i like this" I should turn the second word (since like starts with l, making it a consonant) into 'ikelay' How would I rearrange like so that it became ikel?
I tried to keep your structure while still removing the useless code :
def simple_pig_latin(input_text, sep=" ", end="."):
words = input_text.split(sep)
new_words = []
for word in words:
if word[0].lower() in ['a', 'e', 'i', 'o', 'u']:
new_words.append(word + "way")
else:
new_words.append(word[1:] + word[0] + "ay")
finalstring = sep.join(new_words)
finalstring = finalstring + end
return finalstring
print simple_pig_latin("i like this")
# iway ikelay histay.
Notes :
Your function needs to return something
It's probably easier to create a new list than to mutate the original one
if i is already a string, there's no need to call str(i)
i is usually used for an integer between 0 and n-1. Not for words.
word[0] is the first letter of your word
word[k:] is word without the first k letters
to simplify your code, I consider that if the first letter isn't a vowel, it must be a consonant.
I call lower() on the first letter in order to check if 'I' is a vowel.
For your question, you could change your code str(i) + "ay" to i[1:] + i[0] + "ay" in your elif branch.
Problem 1.
This problem provides practice using a while True loop. Write a function named
twoWords that gets and returns two words from a user. The first word is of a
specified length, and the second word begins with a specified letter.
The function twoWords takes two parameters:
an integer, length, that is the length of the first word and
a character, firstLetter, that is the first letter of the second word.
The second word may begin with either an upper or lower case instance of
firstLetter. The function twoWords should return the two words in a list. Use
a while True loop and a break statement in the implementation of twoWords. The
following is an example of the execution of twoWords:
print(twoWords(4, 'B')):
A 4-letter word please two
A 4-letter word please one
A 4-letter word please four
A word beginning with B please apple
A word beginning with B please pear
A word beginning with B please banana
['four', 'banana']
This is what I have so far, but it keeps asking me the first question over again
even if I have the right word length. What am I doing wrong?
def twoWords(length, firstLetter):
wordLen = input('A 4-letter word please ')
while len(wordLen) != int(length):
wordlen = input('A 4-letter word please ')
word = input('A word beginning with ' + firstLetter + ' please ')
while word[0] != firstLetter:
word = input('A word beginning with ' + firstLetter + ' please ')
return[wordLen, word]
def twoWords(length,firstLetter):
firstWord = ""
secondWord= ""
while True:
firstWord = input('A ' + str(length) + '-letter word please.')
if length == len(firstWord):
break
while True:
secondWord = input('A word beginning with ' + firstLetter+ ' please')
if secondWord[0] == firstLetter.upper() or secondWord[0] == firstLetter.lower():
break
return [firstWord,secondWord]
print(twoWords(4,'B'))
def twoWord(length, firstLetter):
while True:
word1=(input("Enter a "+ str(length)+"-letter word please:"))
if len(word1)==int(length):
break
while True:
word2=input("Please enter the word beginning with "+firstLetter+" please:")
if word2[0].upper()==firstLetter or word2[0].lower()==firstLetter:
break
return word1, word2
print(twoWord(5, 'b'))
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'
This script takes a sentence and encodes it. The code takes each letter in a given word and bumps it up in the alphabet by the length of the word. So "cat" becomes "fwd", "small" becomes "xrfqq", and "small cat" becomes "xrfgg fwd".
I wanted to see if there was anything I should have done differently or if ya'll had some suggestions for improvements.
#Letter altering code
alphabet = ["a","b","c","d","e","f","g","h","i","j",
"k","l","m","n","o","p","q","r","s","t",
"u","v","w","x","y","z"]
textIn= ""
while textIn.lower != 'q':
textIn = input("Type a sentence to be translated ('q' to quit).\n"\
).lower()
textOut = ""
if textIn == 'q':
break
else:
for word in textIn.split():
newWord = ""
for char in word:
if char in alphabet:
pos = alphabet.index(char)
newPos = (pos + len(word))%26
newChar = alphabet[newPos]
newWord += newChar
else:
newWord += char
textOut += newWord + " "
print(textOut)
It's pretty good.
alphabet is string.ascii_lowercase
textIn.lower should be textIn.lower()
break should only be used in a loop. You want pass, which means 'do nothing'.
The loop adding the new character to the new word is clear. I like it. There are other terser ways to do it, though, which are more pythonic and can still be as clear.
This question already has answers here:
Print in one line dynamically [duplicate]
(22 answers)
Closed 8 years ago.
So I am writing a program that asks for your input, puts the words of the sentence you entered into a list and makes the words in the statement go trough the while loop one by one.
The while loops works as follows:
if the first letter of a word is a Vowel it print the word + hay.
Ifthe first letter of the word is not a vowel it puts the first letter of the word at the end of the word + ay
the code:
VOWELS = ['a','e','i','o','u']
def pig_latin(phrase):
#We make sure the input is changed in only lower case letters.
#The words in your sentence are also putted into a list
lowercase_phrase = phrase.lower()
word_list = lowercase_phrase.split()
print word_list
x = 0
while x < len(word_list):
word = word_list[x]
if word[0] in VOWELS:
print word + 'hay'
else:
print word[1:] + word[0] + 'ay'
x = x+1
pig_latin(raw_input('Enter the sentence you want to translate to Pig Latin, do not use punctation and numbers please.'))
My problem:
If i enter for example: "Hello my name is John" in the_raw input at the end of the code i will get the following output:
ellohay
ymay
amenay
ishay
ohnjay
But i actually want the following output:
ellohay ymay amenay ishay ohnjay
If someone could explain me how to achieve this output it would be appriciated
Save the new words in another list, then at the end:
print(" ".join(pig_latin_words))
Example:
VOWELS = {'a','e','i','o','u'}
def pig_latin(phrase):
#We make sure the input is changed in only lower case letters.
#The words in your sentence are also putted into a list
word_list = phrase.lower().split()
print(word_list)
pig_latin_words = []
for word in word_list:
if word[0] in VOWELS:
pig_latin_words.append(word + "hay")
else:
pig_latin_words.append(word[1:] + word[0] + "ay")
pig_latin_phrase = " ".join(pig_latin_words)
print(pig_latin_phrase)
return pig_latin_phrase
Append a comma (,) at the end of your print statements to avoid the newline:
while x < len(word_list):
word = word_list[x]
if word[0] in VOWELS:
print word + 'hay',
else:
print word[1:] + word[0] + 'ay',
x = x+1