How to use spaces in Python with .isalpha() - python

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?

Related

What is the simplest way to capitalize the first word in a sentence for multiple sentences in python 3.7?

For my homework I have tried to get the first word of each sentence to capitalize.
This is for python 3.7.
def fix_cap():
if "." in initialInput:
sentsplit = initialInput.split(". ")
capsent = [x.capitalize() for x in sentsplit]
joinsent = ". ".join(capsent)
print("Number of words capitalized: " + str(len(sentsplit)))
print("Edited text: " + joinsent)
elif "!" in initialInput:
sentsplit = initialInput.split("! ")
capsent = [x.capitalize() for x in sentsplit]
joinsent = "! ".join(capsent)
print("Number of words capitalized: " + str(len(sentsplit)))
print("Edited text: " + joinsent)
elif "?" in initialInput:
sentsplit = initialInput.split("? ")
capsent = [x.capitalize() for x in sentsplit]
joinsent = "? ".join(capsent)
print("Number of words capitalized: " + str(len(sentsplit)))
print("Edited text: " + joinsent)
else:
print(initialInput.capitalize())
This will work if only one type of punctuation is used, but I would like it to work with multiple types in a paragraph.
Correctly splitting a text into sentences is hard. For how to do this correctly also for cases like e.g. abbreviations, names with titles etc., please refer to other questions on this site, e.g. this one. This is only a very simple version, based on your conditions, which, I assume, will suffice for your task.
As you noticed, your code only works for one type of punctuation, because of the if/elif/else construct. But you do not need that at all! If e.g. there is no ? in the text, then split("? ") will just return the text as a whole (wrapped in a list). You could just remove the conditions, or iterate a list of possible sentence-ending punctuation. However, note that capitalize will not just upper-case the first letter, but also lower-case all the rest, e.g. names, acronyms, or words previously capitalized for a different type of punctuation. Instead, you could just upper the first char and keep the rest.
text = "text with. multiple types? of sentences! more stuff."
for sep in (". ", "? ", "! "):
text = sep.join(s[0].upper() + s[1:] for s in text.split(sep))
print(text)
# Text with. Multiple types? Of sentences! More stuff.
You could also use a regular expression to split by all sentence separators at once. This way, you might even be ablt to use capitalize, although it will still lower-case names and acronyms.
import re
>>> ''.join(s.capitalize() for s in re.split(r"([\?\!\.] )", text))
'Text with. Multiple types? Of sentences! More stuff.'
Or using re.sub with a look-behind (note the first char is still lower-case):
>>> re.sub(r"(?<=[\?\!\.] ).", lambda m: m.group().upper(), text)
'text with. Multiple types? Of sentences! More stuff.'
However, unless you know what those are doing, I'd suggest going with the first loop-based version.

title() method in python writing functions when word like aren't

using function
def make_cap(sentence):
return sentence.title()
tryining out
make_cap("hello world")
'Hello World'
# it workd but when I have world like "aren't" and 'isn't". how to write function for that
a = "I haven't worked hard"
make_cap(a)
"This Isn'T A Right Thing" # it's wrong I am aware of \ for isn\'t but confused how to include it in function
This should work:
def make_cap(sentence):
return " ".join(word[0].title() + (word[1:] if len(word) > 1 else "") for word in sentence.split(" "))
It manually splits the word by spaces (and not by any other character), and then capitalizes the first letter of each token. It does this by separating that first letter out, capitalizing it, and then concatenating the rest of the word. I used a ternary if statement to avoid an IndexError if the word is only one letter long.
Use .capwords() from the string library.
import string
def make_cap(sentence):
return string.capwords(sentence)
Demo: https://repl.it/repls/BlankMysteriousMenus
I found this method to be very helpful for formatting all different types of texts as titles.
from string import capwords
text = "I can't go to the USA due to budget concerns"
title = ' '.join([capwords(w) if w.islower() else w for w in text.split()])
print(title) # I Can't Go To The USA Due To Budget Concerns

Program: Words after "G"/"g" (python)

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')]))

Coding a language translator

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.

Remove members of a list in another list

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

Categories

Resources