I am working on a very basic translation program. Currently it can only deal with one letter in a phrase. For example if I were to input "test" it would blurt out "yesy" because it changes "t" to "y". Here's the code I use to do that:
def translate(phrase):
translation = ""
for letter in phrase:
if letter in "t":
translation = translation + "y"
else:
translation = translation + letter
return translation
print(translate(input("Enter word: ")))
Is it possible to add another letter to be translated. So for example "e" to "a" on top of "t" to "y". so that it would spit out "yasy".
There's a much easier way using str.replace: 'test'.replace('t','y').replace('e','a')
However, if you're looking to replace more and more letters str.translate would be more efficient:
from string import maketrans
trans_from = "te"
trans_to = "ya"
trans_model = maketrans(trans_from, trans_to)
'test'.translate(trans_model)
Or, if you want to keep your code, you can use elif:
def translate(phrase):
translation = ""
for letter in phrase:
if letter in "t":
translation = translation + "y"
elif letter in "e":
translation = translation + "a"
else:
translation = translation + letter
return translation
print(translate(input("Enter word: ")))
Use a dictionary.
en-gb = {'t':'y', add more here}
def translate(phrase):
translation = str()
for char in phrase:
translation = translation + en-gb[char]
return translation
Related
First of hopefully many questions to come as I dive deeper into Python. I'm following along to the Giraffe Academy course and have tried to create a more complex program. It's a silly little decoder tool but it's helping me learn a lot of the python basics. I have the first part of the program below:
import string
std = string.ascii_lowercase
rvs = string.ascii_lowercase[::-1]
vwls = {'a':5,'e':1,'i':4, 'o':2, 'u':3}
def translate(phrase):
phrase = phrase.lower()
translation = ""
for letter in phrase:
if letter.isspace() == True:
translation = translation + " "
elif letter in ".!?":
translation = translation + letter
elif letter in vwls:
if str(vwls[letter]) not in translation:
translation = translation + str(vwls[letter])
vwls[letter] = vwls[letter] + 5
else:
indx = std.index(letter)
translation = translation + rvs[indx]
return translation
print(translate(input("Enter a phrase: ")))
My goal is to create the decoder for the output of the previous code. The good news is I know what is causing my problem. Because the message is a string, any vowel that goes past 2 digits wont be picked up by my code below. I need to find a way to include the next character in the string so that it can choose the correct key/value pairing in the dict. Below is what I have so far:
import string
std = string.ascii_lowercase
rvs = string.ascii_lowercase[::-1]
vwls = {'5':'a','1':'e','4':'i','2':'o','3':'u'}
def translate(phrase):
translation = ""
for letter in phrase:
if letter.isspace() == True:
translation = translation + " "
elif letter in ".!?":
translation = translation + letter
elif letter in vwls:
if letter in vwls[letter]:
translation = translation + vwls[letter]
vwls[str(int(letter) + 5)] = vwls[letter]
del vwls[letter]
else:
for index in range(len(phrase)-1):
if phrase[index] == phrase[index+1]:
translation = translation + 'poop'
else:
indx = rvs.index(letter)
translation = translation + std[indx]
return translation
print(translate(input("Enter a phrase: ")))
Any feedback is greatly appreciated! I have tried searching for similar issues and I am still learning the rules for stack overflow so I apologize if I have broken any rules regarding this question.
good luck with your diving
tried here something, not sure if its correct
few points
for each vowel, the %5 is the same, for example u can be 3,8,13,18.. they all have % 5 of 3
the biggest match you can find is the correct one, 23 is either ou or just u after few iteration, so if the dict say u value is 23 the correct value is u
there is a problem with the translate function you provided
eeee is decoded to 1611 which is eee, missing one e
def decode(phrase):
vwls = {'a':5,'e':1,'i':4, 'o':2, 'u':3}
reverse_vwls = {0:'a',1:'e',4:'i',2:'o',3:'u'}
translation = ""
i=0
while i < len(phrase):
if phrase[i].isspace() == True:
translation = translation + " "
i+=1
continue
if phrase[i] in ".!?":
translation = translation + phrase[i]
i+=1
continue
if str.isdigit(phrase[i]): #check if the letter is a digit
tmp_index = i
str_num = ""
while tmp_index<len(phrase) and str.isdigit(phrase[tmp_index]): # take all the co
str_num = str_num+phrase[tmp_index]
tmp_index+=1
int_num = int(str_num) # turn the digits string into int
while int_num:
current_digit = int_num%10
curent_vwl = reverse_vwls[current_digit%5] #the ones digit % 5 is permenent f
if vwls[curent_vwl] == int_num:
vwls[curent_vwl] = vwls[curent_vwl]+5
translation = translation+curent_vwl
i = i+len(str(int_num))
break
int_num = int(int_num/10)
continue
indx = rvs.index(phrase[i])
translation = translation + std[indx]
i+=1
return translation
Why is the variable "translation" assigned to an empty string? Is that because we are going to replace it with the user's input?
def translate(phrase):
translation = ""
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
translation = translation + "G"
else:
translation = translation + "g"
else:
translation = translation + letter
return translation
print (translate(input("Enter a phrase: ")))
In line 6 you have:
translation = translation + "G"
This tries to set translation to whatever string it previously was, but with G at the end. However, at the very start of the loop, what value is translation? How can we add something to it if it doesn't exist yet?
We need to initialize it so that things can be added onto it. That's what setting it to an empty string before the loop is doing.
You're appending "g" and "G" to it. If you don't initialize it, what would you be appending to? - Aplet123
You are doing + to the variable. if you don't initialize it, you'll get UnboundLocalError.
And if you initialize it in the for loop, it will keep resetting the value.
That's why you are assigning at the first part of the function.
And btw, you can use +=
def translate(phrase):
translation = ""
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
translation += "G"
else:
translation += "g"
else:
translation += letter
return translation
print (translate(input("Enter a phrase: ")))
When a variable is assigned, it gets stored somewhere in the memory with an address. If you don't initialize(define) any location for data, how is it supposed to work?
This basic python translator code was supposed to translate every vowel in a letter into G, it does it's job translating vowels into g, but it only translates 2. If I was to write Ga, it translates it into GG, but if I type in Garbo, it only translates it into Gg. What am I doing wrong?
def translate(phrase):
translation = ""
for letter in phrase:
if letter in phrase == "Aeiou" or "aeiou":
translation = translation + letter + 'g'
else:
translation = translation + letter
return translation
print(translate(input("Enter a phrase: ")))
This is a common error. It's because you failed to check the condition for the second string "aeiou". The second operand of or is not a boolean expression but a truthy string. Also the first string must be "AEIOU"
def translate(phrase):
translation = ""
for letter in phrase:
if letter in "AEIOU " or letter in "aeiou":
translation = translation + 'g'
else:
translation = translation + letter
return translation
easy fix, here you go:
def translate(phrase):
translation = ""
for letter in phrase:
if letter.lower() in "aeiou": #.lower() to turn letter into lowercase
translation = translation + "g"
else:
translation = translation + letter
return translation
this turns any vowel into a lowercase g, if you want an uppercase G then replace the "g" with "G"
As per your given code snippet, The below code will work to satisfy your requirement.
def translate(phrase):
translation = ""
for letter in phrase:
if letter.lower() in "aeiou":
translation = translation + "g"
else:
translation = translation + letter
return translation
But if your requirement is just to translate (replace) vowels with "g", then you can do it using regex substitute rather than looping through each letter.
import re
def translate(phrase):
translation = re.sub(r'[AEIOUaeiou]', "g", phrase)
return translation
def translate(phrase):
translation= ""
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
translation = translation + "G"
else:
translation = translation + "g"
else:
translation = translation + letter
return translation
print(translate(input("Enter a phrase: ")))
(This is a program to change vowels to the letter 'g' or 'G' depending if it is upper or lower case)
Why does this work? Since there is a letter.lower() shouldn't it transform that letter to a lowercase one? that way the next if statement ("if letter.isupper():") would never be true...
I'm confused because I only know C and I'm trying to learn Python. In C if I did that it would transform the letter variable to a lower case one so the next if statement would never be true. I'm guessing that functions inside if statements in Python don't change/alter the variables inside those same fucntions...? But then again that wouldn't really make sense to me... What am I thinking wrong?
From https://docs.python.org/3/library/stdtypes.html#str.lower:
Return a copy of the string with all the cased characters converted to lowercase.
letter.lower() does not modify letter when called, it returns a new value.
I wanted to create a translator, so I looked at some videos online and found one that showed how to substitute certain letters in a sentence and turn them into other letters/symbols. I tried doing it and it worked. But once I started adding new other letters for it to look for. It started printing the letter that was supposed to have been substituted.
def translate(phrase):
translation = ""
for letter in phrase:
if letter in "ㅏ": #if ㅏ then A
translation = translation + "A"
if letter in "Б": #if Б then B
translation = translation + "B"
else:
translation = translation + letter
return translation
print(translate(input("Enter a phrase: ")))
I am planning on adding the whole alphabet, so I can't have it print the unwanted "supposed to have been substituted letter". I have tried all I can. But I simply can't get it to work. Any thoughts?
You need to combine the if statements like so:
if letter in "ㅏ": #if ㅏ then A
translation = translation + "A"
elif letter in "Б": #if Б then B
translation = translation + "B"
else:
translation = translation + letter
Otherwise you'll be hitting the else branch for every character other than Б (and that includes ㅏ!)
It might be worth noting that letter in "ㅏ" can be written more simply as letter == "ㅏ". The same goes for the other comparison.
Finally, you might also want to take a look at maketrans() and translate(): https://www.tutorialspoint.com/python3/string_maketrans.htm