This question already has answers here:
python pig latin converter
(2 answers)
Closed 7 years ago.
this is the code I have to make a pig-latin translator and I can't seem to get it to translate, anyone have tips to make this work?
I think that my issue is within the encode and starts with vowel parts but I can't seem to figure this out.
You forgot assign in translate function:
Must be:
phrase = ' '.join(encode(message))
return phrase
In addition to #delimitry's answer, also change the words to word in the if condition of the second function, i.e, change -
if starts_with_vowel(words):
to -
if starts_with_vowel(word):
adjust these 3 functions:
def starts_with_vowel(word):
# return True if the word starts with a vowel and False otherwise
return word[0] in ['a', 'e', 'i', 'o', 'u']
def encode(word):
# translate a single word to the secret language
# call starts with vowel to decide which pattern to follow
if starts_with_vowel(word):
return word[1:] + word[0] + 'ar'
else:
return word + 'way'
def translate(message):
# translate the whole text to the secret language
# call encode to translate individual words in text
return ' '.join(encode(word) for word in message)
the biggest problem was in encode() and starts_with_vowel() iterating through all words (but your comment says it should work on a single word)
Related
This question already has answers here:
python how to uppercase some characters in string
(9 answers)
Closed 4 years ago.
Thanks for your help
Example byron = bYrOn
This is an old homework I'm looking over.
It is actually preety simple to turn all letters in a string to upper case!
just use the variable name and follow .upper() at the end e.g.
byron="byron"
byron=byron.upper()
however, because you want to give only certain letters the "uppercase" status, you'd want to first assign all vowels:
vowels = set(['a','e','i','o','u'])
then use some python logic to do the rest:
for char in byron:
if char in vowels:
Word = Word.replace(char,(char.upper()))
print (Word)
if you want to be quick just copy the code below as it is the complete code used to do your task:
x="byron"
vowels = set(['a','e','i','o','u'])
Word=x
for char in Word:
if char in vowels:
Word = Word.replace(char,(char.upper()))
print(Word)
This question already has answers here:
Check if string appears as its own word - Python
(4 answers)
How to replace multiple substrings of a string?
(28 answers)
Closed 4 years ago.
I want to replace the word 'I' in a sentence by the word 'you', and many other such examples. This is not that difficult, except that the 'I' in a word like 'Instagram' is now also being replaced - which I do not want. I would expect this is very simple but cannot find the solution (I am still inexperienced in programming). Here is my code.
s = 'I can increase my number of Instagram followers'
i = s.split()
i = [i.replace('I', 'you') for i in i]
i = [i.replace('my', 'your') for i in I]
i = " ".join(i)
This gives:
You can increase your number of younstagram followers.
But how do you get this result?
You can increase your number of Instagram followers.
EDIT
I have changed the title of the question
FROM: How to find a word in a string that is not part of another word? Python.
TO: How to replace a word in a sentence ONLY IF that word appears on its own and is not part of another word? Python
This question was marked as a duplicate of Check if string appears as its own word - Python.
However, the answers there only seem to check if a given word appears in a sentence as its own word (not as part of another word) and return a boolean. However, knowing that may be a necessary condition but is not a sufficient condition for replacing that word by something else – which is my goal. Therefore, my question may not be a duplicate of the question it is now linked with.
The following would be simple solutions, but do not work:
i = [i.replace(' I ' , 'you') for i in i] # white space left and right of 'I'
i = [i.replace('''I''', 'you') for i in i]
Any suggestions how to solve this problem?
This question already has answers here:
Best way to strip punctuation from a string
(32 answers)
Closed 6 years ago.
I have been working on a file which has lot of puntuations and we need to neglect the puntuations so we can count the actual length of words.
Example:
Is this stack overflow! ---> Is this stack overflow
While doing this I did wrote a lot of cases for each and every punctuation which is there which made my code work slow.So I was looking for some effective way to implement the same using a module or function.
Code snippet :
with open(file_name,'r') as f:
for line in f:
for word in line.split():
#print word
'''
Handling Puntuations
'''
word = word.replace('.','')
word = word.replace(',','')
word = word.replace('!','')
word = word.replace('(','')
word = word.replace(')','')
word = word.replace(':','')
word = word.replace(';','')
word = word.replace('/','')
word = word.replace('[','')
word = word.replace(']','')
word = word.replace('-','')
So form this logic I have written this, so is there any way to minimize this?
This question is a "classic", but a lot of answers don't work in Python 3 because the maketrans function has been removed from Python 3. A Python 3-compliant solution is:
use string.punctuation to get the list and str.translate to remove them
import string
"hello, world !".translate({ord(k):"" for k in string.punctuation})
results in:
'hello world '
the argument of translate is (in Python 3) a dictionary. Key is the ASCII code of the character, and value is the replacement character. I created it using a dictionary comprehension.
You can use regular expression to replace from a character class as
>>> import re
>>> re.sub(r'[]!,:)([/-]', '', string)
'Is this stack overflow'
[]!,:)([/-] A character class which matches ] or ! or , or etc. Replace it with ''.
This question already has answers here:
Remove specific characters from a string
(2 answers)
Closed 8 years ago.
I'm trying to remove all the vowels from a string, using a function that is passed an argument called "text". I'm not sure if this is the most efficient way to code this, but it's all I could come up with. I'm not sure how to tell the function to check if "text" has any of the characters from the "vowels" list, and if so, to remove it. I thought replacing it with a space would do in the .replace() function would do the trick, but apparently not. The code is supposed to remove lower AND uppercase vowels, so I'm not sure if making them all lowercase is even acceptable. Thanks in advance.
def anti_vowel(text): #Function Definition
vowels = ['a','e','i','o','u'] #Letters to filter out
text = text.lower() #Convert string to lower case
for char in range(0,len(text)):
if char == vowels[0,4]:
text = text.replace(char,"")
else:
return text
Pretty simple using str.translate() (https://docs.python.org/2.7/library/stdtypes.html#str.translate)
return text.translate(None, 'aeiouAEIOU')
Python's Replace has you specify a substring to replace, not a position in the string. What you would want to do instead is
for char in range(0,5):
text = text.replace(vowels[char],"")
return text
UPDATED BASED ON COMMENT:
or you could do
for char in vowels:
text = text.replace(char,"");
return text;
Use the sub() function (https://docs.python.org/2/library/re.html#re.sub):
re.sub('[aeiou]', '', text)
Change your function to loop over the vowels list like this:
def anti_vowel(text): #Function Definition
vowels = ['a','e','i','o','u'] #Letters to filter out
text = text.lower() #Convert string to lower case
for vowel in vowels:
text = text.replace(vowel,"")
return text
This simply iterates over the vowels and replaces all occurrences of each vowel.
This question already has answers here:
def anti_vowel - codecademy (python)
(7 answers)
Closed 8 years ago.
What's wrong with this code? The aim is to check wether the entered string contains vowels and delete them
Here is the code:
def anti_vowel(text):
text = str(text)
vowel = "aeiouAEIOU"
for i in text:
for i in vowel.lower():
text = text.replace('i',' ')
for i in vowel.upper():
text = text.replace('i',' ')
return text
It's a lesson on Codecademy
You are trying to replace the string with the value 'i', not the contents of the variable i.
Your code is also very inefficient; you don't need to loop over every character in text; a loop over vowel is enough. Because you already include both upper and lowercase versions, the two loops over the lowercased and uppercased versions are in essence checking for each vowel 4 times.
The following would be enough:
def anti_vowel(text):
text = str(text)
vowel = "aeiouAEIOU"
for i in vowel:
text = text.replace(i,' ')
return text
You are also replacing vowels with spaces, not just deleting them.
The fastest way to delete (rather than replace) all vowels would be to use str.translate():
def anti_vowel(text):
return text.translate(text.maketrans('', '', 'aeiouAEIOU'))
The str.maketrans() static method produces a mapping that'll delete all characters named in the 3rd argument.