im trying to code a kind of language translator from any language to a kind of gibberish language, wheres every consonant will be replaced with the same consonant plus an o and then the consonant again.
b = bob
d = dod
f = fof
so the text "Hi my name is x"
will become "Hohi momy nonamome isos xox"
The problem i have is the converting part.
any tips on how i can proceed?
Oh and btw I am using python 3
What i got this far.
#Welcom text
print ("Gibberish translator!")
#get stentence
original = raw_input("Give a sentence: ")
#Check so that it is a correct sentence
if len(original) > 0:
print ("")
else:
print ("give a real sentence..: ")
#convert
gibberish = ""
for i in original:
if i == "b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,z":
i = i + "0" + i
gibberish.append(i)
elif i == "a,o,u,e,i,y":
gibberish.append(i)
#print out the gibberish
print (gibberish)
Yeah! i think i got it to work quite well..
# -*- coding: cp1252 -*-
#Repeat
while True :
#Welcom text
print ("Gibberish translator!")
#get stentence
original = raw_input("Give a sentence: ")
#Check so that it is a correct sentence
if len(original) > 0:
print ("")
else:
print ("Give a real sentence..: ")
#convert
gibberish = ""
for i in original:
if i in "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ":
i = i + "o" + i
gibberish = gibberish + i
elif i in "aoueiyåäö AOUEIYÅÄÖ":
gibberish = gibberish + i
#print out the gibberish
print (gibberish)
print ("\n")
Im open for suggestions to make it "better"
The problem is you're comparing a character i to a string "b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,z". The two will never be equal.
What you want to do instead is use the in operator.
if i in 'bcdfghjklmnpqrstvwxz':
Also, strings don't have an .append() method, only lists do.
You can create a string from a list of strings by doing ''.join(my_list)
If and in statements don't work like that. This is actually a very common mistake, so no worries. When you get to the if i == "b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,z": python reads that as "if i is all of this string (the string that contains all the consonants). Now unless you enter that string exactly somewhere in your sentence, python is going to think "nope no string like that" and skip it. You have the same problem with your vowel statements.
For the fastest fix:
if i in "bcdfghjklmnpqrstvwxz": #note the removal of commas, don't want them getting "o'd"
#rest of your code for consonants
else: #having an else is often very good practice, or else you may not get a result.
#what to do if its not a consonant
The function checks if it is a lower case vowel (might want to add stuff for upper case letters), then if it isn't, it checks if it is a letter period. string is very useful when working with strings. You should look at the docs.
And finally, you need to change append to just use + with strings.
Related
I have recently started to learn python as I wanna enter a deep learning field in future.
As I'm completely new and only started I apologize in advance if my question is silly.
I am currently doing a course on edx by name introduction to python fundamentals and as I final project of module 1 I need to make a program that asks for user input and give an output of all words that starts from h to z.
task
here is my code:
user_input = input("enter a 1 sentence quote, non-alpha separate words: ")
new_name = ""
for letter in user_input:
if letter.isalpha() == True:
new_name += letter.upper()
elif letter.isalpha() == False:
if new_name[0] > "g":
print(new_name)
new_name = ""
else:
new_name = "\n"
print(new_name)
INPUT = Wheresoever you go, go with all your heart
OUTPUT = WHERESOEVERYOUGOGOWITHALLYOURHEART
By my understanding of code I have wrote:
- user enters input
- code check for each character
- if letter is alpha that letter is added into new_name variable
- when encounter first no alpha character in these case space after word Wheresoever code moves to elif since after checking a fist one it was not True and elif turn to mach criteria
- then by using nested if statement it checks if new_name variable[index0] (Wheresoever) is grater then g.
- if it is grater it prints new_name and makes new_name empty and repeat the circle until there is no more characters to check.
- if its not greater then g it starts with new word on the new line
Now as I sad I'm completely new so I have just described my thoughts process of the code and please tell me where am I wrong and how can I corrected and improve my thoughts process and the code mentioned above.
Thank you in advance :)
Try the below, iterate trough the list split of the user_input string, then check if it starts with a G or g, if it does, don't keep it, otherwise keep it, then use regular expressions (re) to get only letters.
Also as you said you need isalpha so then:
user_input = input("enter a 1 sentence quote, non-alpha separate words: ")
print('\n'.join([''.join(x for x in i if x.isalpha()).upper() for i in user_input.split() if not i.lower().startswith('g')]))
Example output:
enter a 1 sentence quote, non-alpha separate words: Wheresoever you go, go with your heart
WHERESOEVER
YOU
WITH
YOUR
HEART
Update form #KillPinguin:
do:
user_input = input("enter a 1 sentence quote, non-alpha separate words: ")
print('\n'.join([''.join(x for x in i if x.isalpha()).upper() for i in user_input.split() if ord(i[0])>ord('g')]))
I've been trying to work on this code of mine that takes a string of words, converts every letter into an ASCII code, adds a certain number (rotate_number), and then prints out the translated version of those numbers, all converted back into a string of random letters (but with the spaces and symbols remaining the same). For example, I want the string of "How are you today?" to rotate by a number of say +4, so that the final product says, "Lsa evi csy xshec?"
Here's the code I have so far, however when I run it, only one letter is rotated and printed out:
def encrypt_words(words, rotate_number):
blank = ""
for i in words:
translate1 = ord(i) + rotate_number
translated = chr(translate1)
blank += translated
print translated
encrypt_words("How are you today?", 3)
Also, I am sorry if my question has already been answered. I've been searching all across the web and this specific site, but nothing seems to work for me...
I would recommend first creating a rotate method
def rotate(alphabet,rotation):
return alphabet[rotation:]+alphabet[:rotation]
#test it
print(rotate(string.ascii_lowercase,5))
now create a lookup table of the rotation
def create_lookup_table(rotation,*alphabets):
if not alphabets:
alphabets = [string.ascii_lowercase,string.ascii_uppercase]
alphabet = "".join(alphabets)
rotated = "".join(rotate(a,rotation) for a in alphabets)
return dict(zip(alphabet,rotated))
# test it
create_lookup_table(5)
create_lookup_table(2,"abcdef","GHIJKLM")
now implementing ceasar cipher is trival because we have given ourselves the toolset to help us
def ceasar(msg_plain,rotation):
lookup_table = create_lookup_table(rotation)
return ''.join(lookup_table.get(char,char) for char in msg_plain)
# test it
ceasar("Hello World!",13) # 'Uryyb Jbeyq!'
It looks like you want to be printing the string "blank", not translated as in your code. Try the following:
def encrypt_words(words, rotate_number):
blank = ""
for i in words:
translate1 = ord(i) + rotate_number
translated = chr(translate1)
blank += translated
print blank
Blank is the concatenation of each of the translated values. You should probably rename 'blank' as the name is misleading.
You would want to do something like :
def encrypt_words(words, rotate_number):
blank = ""
for i in words:
if i.isalpha(): # if part of alphabet shift with cipher
translate1 = ord(i) + rotate_number
translated = chr(translate1)
blank += translated
else: # else leave as is
blank += i
print blank # print entire word, not just last character
# change blank variable to something that better describes function?
I am currently learning Python with Codecademy, and they have a project there called "PygLatin translator". I have made the same thing from scratch(to test my knowledge) and it works, but only 1 word at a time.
Due to it using the .isalpha() function, if you put spaces inside the input box, it says that it is not allowed(as spaces are not alphabetical characters).
For example:
Python --> ythonPay
Python is Cool --> rejected
Are there currently any ways to fix this?
Also, 1 more thing: I am using Python version 2.7.3, because I read somewhere that it is more noob-friendly.
This is my code:
pyg = "ay"
print "Welcome to the English --> (really weak) Encrypter!"
name = raw_input("Enter a word. ")
if len(name) > 0 and name.isalpha():
word = name.lower()
first = name[0]
new_word = word[1:] + first + pyg
print new_word
elif len(name) == 0:
print "You haven't typed in anything."
else:
print "You can only use alphabetical characters. No spaces, I am working on that."
In general, yes: use the built-in string methods. Use the split method to break the input into individual words. Translate each individually. Paste them back together with the join method. For instance:
text = input( ... )
word_list = text.split()
# Translate each word individually.
pig_latin = ' '.join(translated_word_list)
Does that get you moving?
I'm writing a program that checks if a word or sentence given by user input is a palindrome or not. This is the program so far:
def reverse(text):
a = text[::-1]
if a == text:
print "Yes, it's a palindrome."
else:
print "No, it's not a palindrome."
string = str(raw_input("Enter word here:")).lower()
reverse(string)
However, this code doesn't work for sentences. So I tried to do it like this:
import string
def reverse(text):
a = text[::-1]
if a == text:
print "Yes, it's a palindrome."
else:
print "No, it's not a palindrome."
notstring = str(raw_input("Enter word here:")).lower()
liststring = list(notstring)
forbiddencharacters = string.punctuation + string.whitespace
listcharacters = list(forbiddencharacters)
newlist = liststring - listcharacters
finalstring = "".join(newlist)
reverse(finalstring)
My goal is to put the punctuation and whitespace into a list and then subtracting those characters to the input of the user so that the program can tell if it's a palindrome even if the string has punctuation and/or whitespace. However, I don't know how I can subtract the elements in a list to the elements in another list. The way I did it, by creating another list that equals the user input minus the characters doesn't work (I tried it in my Xubuntu terminal emulator). Apart from that, when I run the program this error appears:
Traceback (most recent call last):
File "reverse.py", line 12, in <module>
forbiddencharacters = string.punctuation + string.whitespace
AttributeError: 'str' object has no attribute 'punctuation'
Ok so I have changed the variable name and I don't get that mistake above. Now I still don't know how to subtract the elements of the lists.
Since I'm a beginner programmer this might seem stupid to you. If that's the case, I'm sorry in advance. If anyone can solve one or both of the two problems I have, I'd be extremely grateful. Thanks in advance for your help. Sorry for bad english and long post :)
You should add some filtering along the way since palindromes have various syntax tricks (spaces, commas, etc.).
palindrome = "Rail at a liar"
def is_palindrome(text):
text = text.lower() #Avoid case issues
text = ''.join(ch for ch in text if ch.isalnum()) #Strips down everything but alphanumeric characters
return text == text[::-1]
if is_palindrome(palindrome):
print "Yes, it's a palindrome."
else:
print "No, it's not a palindrome."
You are on the right track, but you have used the identifier string for two different purposes.
Since you assigned to this variable name with the line:
string = str(raw_input("Enter word here:")).lower()
You can now no longer access the attributes string.punctuation and string.whitespace from the import string, because the name string is no longer bound to the module but to the user input instead.
A somewhat different approach to testing if a string is a palindrome
def palindrome(s):
s = s.lower()
ln=len(s)
for n in xrange(ln/2):
if s[n] != s[(ln-n)-1]:
return False
return True
print palindrome('Able was I ere I saw Elba')
FYI -- you'll need to tweak this to strip punctuation and white space if you like (left an an exercise to OP)
You can do that by splitting the phrase and storing it in a list. I am going to use your function (but there are more better pythonic ways to do that).
def reverse(textList1):
textList2 = textList1[::-1] #or we can use reversed(textList1)
if textList2 == text:
print "Yes, it's a palindrome."
else:
print "No, it's not a palindrome."
test1= "I am am I"
You should split the phrase and store it in a list:
test1List= test1.split(' ')
reverse(test1List)
Checking for palindrome is simple,
This works for both words and sentences.
import string
def ispalindrome(input_str):
input_str = list(input_str)
forbidden = list(string.punctuation + string.whitespace)
for forbidden_char in forbidden: # Remove all forbidden characters
while forbidden_char in input_str:
input_str.remove(forbidden_char)
return input_str == list(reversed(input_str)) # Checks if it is a palindrome
input_str = raw_input().lower() # Avoid case issues
print ispalindrome(input_str) # Get input
I was studying Python on this website www.codacademy.com and I'm stuck on exercise PygLatin in part 4 of 12.
"Write an if statement that checks to see if the string is not empty.
If the string is not empty, print the user's word.
Otherwise (else), print "empty" if the string is empty.
Make sure you thoroughly test your code. You'll want to make sure you run it multiple times and test both an empty string and a string with characters. When you are confident that your code works, continue on to the next exercise."
I have to print the user's input word if he does so, if not, print "empty".
original = raw_input("Welcome to the English to Pig Latin translator! Type in the word you wish to use.")
if len(original) > 0:
return raw_input
else:
return "empty"
print original
But it's not working, I need help.
What am I doing wrong? The error claims it's on line 2 (if len(original) > 0:) but I haven't figured out what's wrong.
Wrong indentation is the main problem. Also, you have return statements but don't have a function. Plus, you can simplify the check if original is empty:
original = raw_input("Welcome to the English to Pig Latin translator! Type in the word you wish to use.")
if original:
print original
else:
print "empty"
or, in one line:
print original if original else "empty"
or:
print original or "empty"
You have two main problems: indentation and return without a function.
If you want to use a function, you could define a function that receive a string parameter, checks if it's empty, and then returns the corresponding string.
For example:
def checkstring(string):
if len(string) > 0:
return string
else:
return "empty"
original = "Welcome to the English to Pig Latin translator! Type in the word you wish to use."
print checkstring(original)
You can't indent arbitrarily in Python. The four lines beginning with the if statement are indented one level further than the first statement: that's not allowed. You can only indent after a statement that introduces a new block, as you have done after if and else. Bring those four lines back a level so that they start at the left-hand side.
I got the code from "Quine"but I edited more so you can actually put the input. Works better if you ask me for the purpose of this exercise:
print "Welcome to the English to Pig Latin translator!"
def checkstring(original):
if len(original) > 0:
return original
else:
return "empty"
original = raw_input("What is your name?")
print checkstring(original)
print 'Welcome to the Pig Latin Translator!'
# Start coding here!
raw_input ("What is your name")
variable_name = raw_input ()
original = raw_input()
if len (original) > 0:
print "the user's word"
else:
print "empty"