Basic translator, that translates a vowel into a g - python

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

Related

Assigning empty quotes to a variable python

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?

string.lower() in an if loop doesn't lower case the string in Python?

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.

Translate/Replace Multiple Letters With Python

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

Filter words in a sentence that begin with a certain range of letters

My task is to print all words in a sentence whose first letter is within a range of letters, for example: h-z.
This is my code so far, however it still prints words which begin with "g" and does not print the last word.
famous_quote = input("Enter a one sentence quote: ").lower()
word = ""
for ltr in famous_quote:
if ltr.isalpha() == True:
word = word + ltr
else:
if word > "g":
print(word)
word = ""
else:
word = ""
I'm only allowed to use ASCII comparisons, I've tried to compare the ASCII values but I don't know how to go about it in this context.
Sample input:
Wheresoever you go, go with all your heart
Sample output:
WHERESOEVER
YOU
WITH
YOUR
HEART
Algorithm I've come up with:
- split the words by building a placeholder variable: word
- Loop each character in the input string
- check if character is a letter
- add a letter to word each loop until a non-alpha char is encountered
- if character is alpha
- add character to word
- non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to else
- else
- check if word is greater than "g" alphabetically
- print word
- set word = empty string
- or else
- set word = empty string and build the next word
- Hint: use .lower()
You can define a neat little generator to split your sentence into words and compare the first letter of each.
def filter_words(sentence, lo, hi):
lo, hi = map(str.upper, (lo, hi))
words = sentence.upper().split()
for word in words:
if lo <= word[0] <= hi:
yield word
sentence = 'Wheresoever you go, go with all your heart'
print(*filter_words(sentence, 'h', 'z'), sep='\n')
WHERESOEVER
YOU
WITH
YOUR
HEART
This is how I approached this problem. It gave me a hard time since I am a beginer. But it seems to work fine.
quote = "quote goes here"
word = ""
for letter in quote:
if letter.isalpha():
word += letter
else:
if word > "":
print(word.upper())
word = ""
else:
word = ""
print(word.upper())
I added the space to the user_input and also used the word > 'h'. Below is how it looks:
user_input = input('Enter a phrase: ').lower()
user_input += ' '
word = ''
for char in user_input:
if char.isalpha():
word += char
else:
if word > 'h':
print(word.upper())
word = ''
else:
word = ''
This code worked for me...
The task is: Create a program inputs a phrase (like a famous quotation) and prints all of the words that start with h-z
I was making the mistake of using word > "g" before, which needs to be replaced by word > "h".
Also, you need to add the last print command in order to print the last word in case the phrase does not end with a punctuation (as in the given example)
phrase = input ("Please enter a phrase: ").lower()
word = ""
for letter in phrase:
if letter.isalpha():
word += letter
else:
if(word > "h" ):
print(word)
word = ""
else:
word = ""
if word.lower() > 'h':
print(word)
Just one comment on the exercise, as a programming exercise this approach is fine but you would never do it this way in practice.
The two issues you've highlighted is that you are comparing the whole word instead of just the first character.
Simply change:
if word > "g":
To:
if word and word[0] > "g":
And if the quote doesn't finish with a punctuation you will miss the last word off, just add after the loop:
if word:
print(word)
You may note the output is all uppercase, so .lower() the whole quotation may be an issue, alternatively you can just .lower() the comparison, e.g.:
famous_quote = input("Enter a one sentence quote: ")
...
if word and word[0].lower() > "g":
Note: You can simplify your else: condition:
else:
if word and word[0] > "g":
print(word)
word = ""
You stated that you are not allowed to use the split() method. I am not sure what you can use, so here's a solution (not the optimal one).
famous_quote = input("Enter a one sentence quote:") + ' '
current_word = None
for c in famous_quote:
if ('a' <= c <= 'z') or ('A' <= c <= 'Z'):
if current_word is None:
current_word = c # start a new word
else:
current_word += c # append a new letter to current word
else:
if current_word is not None:
f = current_word[0] # first letter
if ('h' <= f <= 'z') or ('H' <= f <= 'Z'):
print(current_word)
current_word = None
Here is a sample run of the program. It preserves lowercase and uppercase. It also splits words on any non-ASCII character.
Enter a one sentence quote: Whereever you go, there you are!!!
Whereever
you
there
you
Note: Since printing is done when a non-ASCII character is encountered, a non-ASCII character is appended at the end of famous_quote.
Assuming that the famous quote contains only spaces as word separator, this should do the job:
words = input("Enter a one sentence quote: ").lower().split()
for word in words:
if word[0] > 'g':
print("{w} ".format(w = word))
split() transforms a string into a list (array). It takes, by default, the space character as parameter (hence I did not give the argument) and returns the list of words.
print() can be used in a lot of ways, due to python's history with this function.
You can .join() the list (getting a string as result) and print it:
print(" ".join(words))
you can also print with concatenations (considered ugly):
print(word+" ")
or you can use formatted printing, which I do use a lot for readibility:
print("{w} ".format(w = word))
interprets "{w}" and replaces it with word wherever "{w}" appears.
Print formatting is rather CPU consuming (but it is still really fast). Usually any print operation slows your application, you want to minimize making outputs if you are making CPU intensive apps in your future (here I don't do that because CPU is not the main concern).
1. Split the words by building a placeholder variable: word
Loop each character in the input string
and check if character is a letter. Then add letter to the variable "word". Loop until a non-alpha char is encountered.
2. If character is alpha or (alphabet)
Add character to word.
Non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to the "else" part.
input_quote = input("Enter a 1 sentence quote, non - alpha seperate words: ")
word = ""
for character in input_quote:
if character.isalpha():
word += character
3. Else
Check if word is greater than "g" alphabetically. Print word and set "word = empty" string.
else:
if word and word[0].lower() >= "h":
print("\n", word.upper())
word = ""
4. Or else
Set word = empty string and build the next word.
else:
word = ""
if word.lower() >= "h":
print("\n", word.upper())
The last "if" is explicitly coded to print the last word if it doesn't end with a non-alpha character like a space or punctuation.
I did this exact same problem. The issue most people are having (and no one seemed to point out) is when you encounter double punctuations or a punctuation followed by a space.
This is the code I used.
phrase = input("Please enter a famous quote: ")
word = ""
for letter in phrase:
if letter.isalpha() is True:
word += letter
elif len(word) < 1: <--- [This is what accounts for double punctuations]
word = ""
elif word[0].lower() >= "g":
print(word)
word = ""
else:
word = ""
print(word) <--- [accounts for last word if not punctuated]
Variable "word" already contains your last word of the phrase but since it does not fulfil the condition to enter the loop it does not gets printed. So you can check the below solution.
phrase = input("Enter a phrase after this: ")
word = ""
for char in phrase:
if char.isalpha():
word += char
else:
if word != "":
if word[0].lower() >= "h":
print(word.upper())
word = ""
else:
word = ""
if word[0].lower() >= "h":
print(word.upper())
This code works for me:
phrase=input("Enter a one sentence quote,non-alpha separate words: ")
word=""
for character in phrase:
if character.isalpha():
word+=character
else:
if word.lower()>="h".lower():
print(word.upper())
word="" -----this code defines the end of a word
else:
word=""
print(word.upper()) ------this will print the last word
I would use regular expressions and list compreshension as shown in the function below.
def words_fromH2Z():
text = input('Enter a quote you love : ')
return [word for word in re.findall('\w+', text) if not word[0] in list('aAbBcCdDeEfFgG')]
When I test the function by putting in the input "I always Visit stack Overflow for Help", I get:
words_fromH2Z()
Enter a quote you love : I always Visit stack Overflow for Help
['I', 'Visit', 'stack', 'Overflow', 'Help']
This worked well for me. I had to add the last two lines of code because without them, it wasn't printing the last word, even if it began with a letter between h and z.
word = ""
quote = input("Enter your quote")
for char in quote:
if char.isalpha():
word += char
elif word[0:1].lower() > "g":
print(word.upper())
word = ""
else:
word = ""
if word[0:1].lower() > "g":
print(word.upper())
famous_quote = input("Enter a one sentence quote:")
current_word = None
for c in famous_quote:
if c.isalpha():
if (c >= 'a') or (c >= 'A'):
if current_word is None:
current_word = c
else:
current_word += c
else:
if current_word is not None:
f = current_word[0]
if ('h' <= f <= 'z') or ('H' <= f <= 'Z'):
print (current_word.upper())
current_word = None
if famous_quote[-1].isalpha():
print (current_word.upper())

How to flag first occurrence of a vowel, move preceding consonants to end

I've been instructed to create a PygLatin translator in Python - I'm very much a beginner. I have to translate any random input sentence. As of now, I need to be able to flag the first occurrence of a vowel in a word and transfer all the consonants preceding to the end of that word.
def encrypt():
modify_split = list(sentence.split())
letter = list(word)
for letter in word:
if letter == "A":
print(word[1:] + "*" + word[0:1] + "AY")
if letter == "E":
print(word[1:] + "*" + word[0:1] + "AY")
if letter == "I":
print(word[1:] + "*" + word[0:1] + "AY")
if letter == "O":
print(word[1:] + "*" + word[0:1] + "AY")
if letter == "U":
print(word[1:] + "*" + word[0:1] + "AY")
It is currently printing every word per letter in the sentence, and not splitting at the vowel at all. Is there a simple way for it to loop through a list, find the vowel, and let me split the word there? Thanks in advance!
EDIT:
Sample input:
"Computer science is great"
Expected output:
"omputer*cay ience*scay is*~way eat*gray"
Setup your vowels in a string then using enumerate once you encounter a character that is in vowels you can store its index to slice your original string
s = 'this'
vowels = 'aeiou'
for i, v in enumerate(s):
if v.lower() in vowels:
x = i
break
print(s[x:] + s[:x]) # => isth
Replace word[1:] with word[length:] and word[0:1] with word[0:length]
You want to use length because that is the current index of the loop. word[length:] will then give you all the letters in the word starting from the index of that vowel, and word[0:length] will give you the letters in the string up until that vowel.

Categories

Resources