I am trying to expand on the Codecademy pig latin convertor so that it accepts sentences rather than just single words and converts each word in the sentence. Here's the code that I have:
pyg = 'ay'
pyg_input = raw_input("Please enter a sentence: ")
print
if len(pyg_input) > 0 and pyg_input.isalpha():
lwr_input = pyg_input.lower()
lst = lwr_input.split()
for item in lst:
frst = lst[item][0]
if frst == 'a' or frst == 'e' or frst == 'i' or frst == 'o' or frst == 'u':
lst[item] = lst[item] + pyg
else:
lst[item] = lst[item][1:len(lst[item]) + frst + pyg
print ' '.join(lst)
I'm not sure what is wrong so I am grateful of any help.
Thanks
Sentence can contain non-alphabet (for example space): so pyg_input.isalpha() will yield False:
You're using lst[item] to access each character. Instead use item.
You cannot update list while you iterate the list. In the following code I used another list called latin.
Your code have a SyntaxError in following line (no closing braket):
lst[item][1:len(lst[item])
The following code is not perfect. For example, you need to filter out non-alphabet such as ,, ., ...
pyg = 'ay'
pyg_input = raw_input("Please enter a sentence: ")
print
if len(pyg_input) > 0:# and pyg_input.isalpha():
lwr_input = pyg_input.lower()
lst = lwr_input.split()
latin = []
for item in lst:
frst = item[0]
if frst in 'aeiou':
item = item + pyg
else:
item = item[1:] + frst + pyg
latin.append(item)
print ' '.join(latin)
I have tried the below way to implement the pyg_latin translator
import enchant
input_str = raw_input("Enter a word:")
d = enchant.Dict("en_US")
d.check(input_str)
pyg_latin = input_str[1:]+input_str[0]+"ay"
print pyg_latin
Related
I'm trying to do the following function: We need to build a list out of a string. The list should only have alphabetical characters in it.
#if the input is the following string
mystring = "ashtray ol'god for, shure! i.have "
#the output should give a list like this:
mylist = ['ashtray','ol','god','for','shure','i','have']
No modules should be imported. I created the following function and it works, but I would be happy if someone could provide a better way to do it.
for ch in mystring:
if ch.isalpha() == False:
mystring = mystring.replace(ch,' ')
mylist = mystring.split()
by alphabetical character I mean all alphabetical characters present in UTF8, that means including arabic ,jewish chars etc.
Try this code
mystring = "ashtray ol'god for, shure! i.have "
lst = []
mystr = ''
for i in mystring:
temp = ord(i)
if (65 <= temp <= 90) or (97 <= temp <= 122):
mystr += i
else:
if mystr:
lst.append(mystr)
mystr = ''
print(lst)
Or
mystring = "ashtray ol'god for, shure! i.have "
lst = []
mystr = ''
for i in mystring:
if i in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz':
mystr += i
else:
if mystr:
lst.append(mystr)
mystr = ''
print(lst)
Or (including Non-English characters)
mystring = "ashtray ol'god for, shure! i.have "
lst = []
mystr = ''
for i in mystring:
if i.isalpha():
mystr += i
else:
if mystr:
lst.append(mystr)
mystr = ''
print(lst)
Output:
['ashtray', 'ol', 'god', 'for', 'shure', 'i', 'have']
Tell me if its not working...
For this problem, I am given strings ThatAreLikeThis where there are no spaces between words and the 1st letter of each word is capitalized. My task is to lowercase each capital letter and add spaces between words. The following is my code. What I'm doing there is using a while loop nested inside a for-loop. I've turned the string into a list and check if the capital letter is the 1st letter or not. If so, all I do is make the letter lowercase and if it isn't the first letter, I do the same thing but insert a space before it.
def amendTheSentence(s):
s_list = list(s)
for i in range(len(s_list)):
while(s_list[i].isupper()):
if (i == 0):
s_list[i].lower()
else:
s_list.insert(i-1, " ")
s_list[i].lower()
return ''.join(s_list)
However, for the test case, this is the behavior:
Input: s: "CodesignalIsAwesome"
Output: undefined
Expected Output: "codesignal is awesome"
Console Output: Empty
You can use re.sub for this:
re.sub(r'(?<!\b)([A-Z])', ' \\1', s)
Code:
import re
def amendTheSentence(s):
return re.sub(r'(?<!\b)([A-Z])', ' \\1', s).lower()
On run:
>>> amendTheSentence('GoForPhone')
go for phone
Try this:
def amendTheSentence(s):
start = 0
string = ""
for i in range(1, len(s)):
if s[i].isupper():
string += (s[start:i] + " ")
start = i
string += s[start:]
return string.lower()
print(amendTheSentence("CodesignalIsAwesome"))
print(amendTheSentence("ThatAreLikeThis"))
Output:
codesignal is awesome
that are like this
def amendTheSentence(s):
new_sentence=''
for char in s:
if char.isupper():
new_sentence=new_sentence + ' ' + char.lower()
else:
new_sentence=new_sentence + char
return new_sentence
new_sentence=amendTheSentence("CodesignalIsAwesome")
print (new_sentence)
result is codesignal is awesome
Probelm Description:
sms_encoding() which accepts a sentence and converts it into an abbreviated sentence to be sent as SMS and returns the abbreviated sentence.
Rules are as follows:
a. Spaces are to be retained as is
b. Each word should be encoded separately
If a word has only vowels then retain the word as is
If a word has a consonant (at least 1) then retain only those consonants
My Code:
#PF-Assgn-50
def sms_encoding(data):
#start writing your code here
vowels=set("aeiouAEIOU")
v_list=[]
c_list=[]
final_list=[]
new_string=''
word=data.split()
word2=[]
for i in range(0,len(word)):
ch=word[i]
#print(ch)
if ch in vowels:
v_list.append(ch)
for letter in word[i]:
if letter not in vowels:
c_list.append(letter)
c_list.append(" ")
new_string=''.join(v_list)+''.join(c_list)
final_list.append(new_string)
#print(v_list)
return ' '.join(final_list)
data="Have a Nice Day"
print(sms_encoding(data))
My Output:
aHv **<2spaces>** Nc **<1space>** Dy
Expected Output:
Hv a Nc Dy (contains only 1 space)
You could iterate over words in the sentence taking only consonants only if the word contains atleast one consonant:
data = "Have a Nice Day"
splitted = data.split()
for i, x in enumerate(splitted):
if not all(y in 'aeiou' for y in x.lower()):
splitted[i] = ''.join([y for y in x if y.lower() not in 'aeiou'])
print(' '.join(splitted))
# Hv a Nc Dy
This will work for all cases... retains all except vowels when even 1 character in a string is not vowel.
def sms_encoding(data):
vowels = set("aeiouAEIOU")
words = data.split()
encoded_words = []
for i in range(0,len(words)):
vow_count = 0
cons_word = []
for x in words[i]:
if x in vowels:
vow_count =vow_count+1
elif x not in vowels:
cons_word.append(x)
if vow_count == len(words[i]):
encoded_words.append(words[i])
elif vow_count != len(words[i]):
encoded_words.append("".join(cons_word))
encoded_msg = " ".join(encoded_words)
return encoded_msg
data=input("Kindly enter your message for sms encoding : ")
print(sms_encoding(data))
Try and let me know!
def sms_encoding(data):
vowel = "aeiouAEIOU"
list1 = data.split()
list2 = []
for i in list1:
length=len(i)
if length == 1:
list2.append(i)
list2.append(" ")#to add spaces between the words
else:
count=0
for a in i:
if a in vowel:
count+=1
if count==length: #to check if all the letters are vowels
list2.append(i)
list2.append(" ")
for a in i:
if a not in vowel:
list2.append(a)
list2.append(" ")
list2.pop() #to remove the extra space at the end of the whole sentence
q="".join(list2)
return q
data = "I love Python aeio"
print(sms_encoding(data))
try this code it will work the question is from infytq
def sms_encoding(data):
data=data.lower()
a=data.split()
v1=""
for i in range(0,len(a)):
z=a[i]
v=""
c1=0
for j in z:
if j not in ('a','e','i','o','u'):
v=v+j
elif j in ('a','e','i','o','u'):
c1=c1+1
if(c1!=len(z)):
v1=v1+v+" "
elif(c1==len(z)):
v1=v1+z+" "
word=v1[0:len(v1)-1]
return word
data="I love Python"
print(sms_encoding(data))
def sms_encoding(new_s):
encrypt_string = []
consonant_list = []
vowel_set = set("aeiouAEIOU")
for word in range(0, len(new_s)):
v_letter = new_s[word]
if v_letter in vowel_set:
encrypt_string.append(v_letter)
for letter in v_letter:
if letter not in vowel_set:
consonant = " ".join(letter)
encrypt_string.append(consonant)
encrypt_string.append(" ")
encrypt_string = "".join(encrypt_string)
print(encrypt_string)
s = input("Enter a string ")
new_s = s.split()
sms_encoding(new_s)
Using the Codecademy pyglatin.py translator as an example, I am trying to expand the translator to include multiple words at a time.
So far, it reads the first word and translates it, and I would like to continue onto the next word, and then the next, until no more words exist. I would then like to print the entire original translated input.
def piglatin():
pig = 'ay'
original = raw_input('Enter a phrase:').split(' ')
if len(original[0]) > 0 and original[0].isalpha():
word = original[0].lower()
first = word[0]
if first == "a" or first == "e" or first == "i" or first == "o" or first =="u":
new_word = word + pig
print new_word
else:
new_word = word[1:] + word[0:1] + pig
print new_word
again = raw_input('Translate again? Y/N')
print again
if len(again) > 0 and again.isalpha():
second_word = again.lower()
if second_word == "y":
return piglatin()
else:
print "Okay Dokey!"
else:
print 'Letters only please!'
return piglatin()
Thanks!
You want a for loop. A good starting point would be:
for word in original:
Here is my code for the pig latin translator. It works both on Code academy and in linux terminal.
pyg = 'ay'
new_word = pyg
original = raw_input('Enter a word: ')
if len(original) > 0 and original.isalpha():
original.lower()
word = original
first = original[0]
if first == 'a' or first =='e' or first == 'i' or first =='o' or first == 'u':
print 'vowel'
elif first != 'a' or first !='e' or first !='o' or first !='i' or first !='u':
print word.lower()[1:] + first +new_word
else:
print 'empty'
Code academy gives following result;
Oops, try again! Your word started with a consonant, but “ay' was printed instead of “ogday”. Make sure the correct value #is stored in “new_word”.
"ay" is not printed but "ogday' is printed.
Does anyone know how to fix this? I cannot continue with Codeacademy as without solving this.
You can do something like this for example. You are in the right track just use what you have learned in the Code academy up to this task.
consonants = "bcdfghjklmnpqrstvxz"
original = raw_input('Enter a word: ')
if len(original) > 0 and original.isalpha():
if original.lower()[0] in 'aeiou':
print original.lower() + 'ay'
else:
keep_first_consonants = ''
count = 0
for letter in original.lower():
if letter in consonants:
keep_first_consonants = keep_first_consonants + letter
count += 1
else:
break
total_characters = len(original.lower())
print original.lower()[count:total_characters] + keep_first_consonants + 'ay'
else:
print 'Accept only letters'
The codeacademy lesson checker seems to check the variable new_word when you hit run
So you just need to use new_word for both your print varibles
This code works:
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
if first == "a" or first == "e" or first == "i" or first == "o" or first == "u":
new_word = original + pyg
print new_word
else:
newer_word = word[1:]
new_word = newer_word + first + pyg
print new_word