Deleting vowels in string in python: - python

The code:
def anti_vowel(text):
string1 = list(text)
for i in string1:
if i=='A'or i=='a' or i=='E'or i=='e'or i=='O'or i=='o' or \
i=='I'or i=='i' or i=='U' or i=='u':
del(string1[string1.index(i)])
string2 = ''.join(string1)
return string2
Gives an error:
Your function fails on anti_vowel("Hey look Words!").
It returns "Hy lk Words!" when it should return "Hy lk Wrds!".
I don't know how to delete that "o" in "words". Can you tell me what's wrong?

If you just want to remove vowels from strings this is an easy way to do it:
word = "hello world"
w = filter(lambda x: x not in 'aeiouAEIOU', word)
print w
Output:
hll wrld

This looks like a good place to be using regular expressions...
import re
re_vowels = re.compile(r'[AaEeIiOoUu]')
def anti_vowel(text):
return re_vowels.sub('', text)
Results in 'hy lk Wrds!'
But if you have to fix the code you have, try this...
def anti_vowel(text):
string1 = list(text)
for c in xrange(len(string1)-1,-1,-1):
i = string1[c]
if i=='A'or i=='a' or i=='E'or i=='e'or i=='O'or i=='o' or \
i=='I'or i=='i' or i=='U' or i=='u':
del(string1[c])
string2 = ''.join(string1)
return string2
Or...
def anti_vowel(text):
return ''.join([c for c in text if c.lower() not in 'aeiou'])
In your code you are trying to delete something that doesn't exist anymore. If you are going to iterate through a list while deleting elements, iterate through it in reverse order (or use list comprehensions).

your code is messy and not nice you can do it a easy way by setting vowels and comparing them to the value like below. This then will do a replace on the vowels which match in the string.
def anti_vowel(text):
string1 = text
vowels = ('a', 'e', 'i', 'o', 'u')
for x in text.lower():
if x in vowels:
string1 = string1.replace(x,"")
return string1

Related

Return a list of words that contain a letter

I wanna return a list of words containing a letter disregarding its case.
Say if i have sentence = "Anyone who has never made a mistake has never tried anything new", then f(sentence, a) would return
['Anyone', 'has', 'made', 'a', 'mistake', 'has', 'anything']
This is what i have
import re
def f(string, match):
string_list = string.split()
match_list = []
for word in string_list:
if match in word:
match_list.append(word)
return match_list
You don't need re. Use str.casefold:
[w for w in sentence.split() if "a" in w.casefold()]
Output:
['Anyone', 'has', 'made', 'a', 'mistake', 'has', 'anything']
You can use string splitting for it, if there is not punctuation.
match_list = [s for s in sentence.split(' ') if 'a' in s.lower()]
Here's another variation :
sentence = 'Anyone who has never made a mistake has never tried anything new'
def f (string, match) :
match_list = []
for word in string.split () :
if match in word.lower ():
match_list.append (word)
return match_list
print (f (sentence, 'a'))

why my code does not decode the encrypted string based on the dictionary?

I have a dictionary with keys and values that represent letters.
for example a simple one :
DICT_CODE = {'b' : 'g', 'n' :'a', 'p' : 'o', 'x' : 'd', 't' : 'y'}
I've received an encrypted code and turned the string into a list, where each item is a word. I need to solve it, according to the items in the dictionary.
an example for a code is :
words_list = ["bppx","xnt!"] # "good day!"
I've tried to solve it by using double for loops, as here:
for word in words_list:
for char in word:
if char in string.letters:
word = word.replace(char, DICT_CODE.get(char))
print words_list
expected output -> ["good","day!"]
output -> ["bppx","xnt!"]
It does not working at all. the charcaters stay the same and the code is stil unknown.
I don't understand why it isn't working, if someone has time to look and try to help me and see whats wrong, or even suggest a better way (that works).
Changing the word variable inside the for loop, would not change the string inside the word_list. You would need to remember the index and update the element at that index (and get the word from the index) -
for i, word in enumerate(words_list):
for char in word:
if char in string.letters:
words_list[i] = words_list[i].replace(char, DICT_CODE.get(char))
Demo -
>>> words_list = ["bppx","xnt!"]
>>> DICT_CODE = {'b' : 'g', 'n' :'a', 'p' : 'o', 'x' : 'd', 't' : 'y'}
>>> for i, word in enumerate(words_list):
... for char in word:
... if char in string.letters:
... words_list[i] = words_list[i].replace(char, DICT_CODE.get(char))
>>> words_list
['good', 'day!']
But an easier way for you would be to use str.translate (along with string.maketrans ). Example -
table = string.maketrans('bnpxt','gaody') #First argument characters in your original string, and second argument what they map to.
for i, word in enumerate(words_list):
words_list[i] = word.translate(table)
Demo -
>>> import string
>>> table = string.maketrans('bnpxt','gaody') #This creates the translation table
>>> words_list = ["bppx","xnt!"]
>>> for i, word in enumerate(words_list):
... words_list[i] = word.translate(table)
...
>>> print words_list
['good', 'day!']
This using list comprehension -
words_list[:] = [word.translate(table) for word in words_list]
Demo -
>>> words_list = ["bppx","xnt!"]
>>> table = string.maketrans('bnpxt','gaody')
>>> words_list[:] = [word.translate(table) for word in words_list]
>>> words_list
['good', 'day!']
Your problem is that you don't actually modify original list.
for i, word in enumerate(words_list):
for char in word:
if char in string.letters:
word = word.replace(char, DICT_CODE.get(char))
words_list[i] = word
print words_list
['good', 'day!']
As mentioned in the comments, by #marmeladze, print word_list will print the word_list which you declared above.
What you want, is something like this:
DICT_CODE = {'b' : 'g', 'n' :'a', 'p' : 'o', 'x' : 'd', 't' : 'y', '!': '!'}
words_list = ["bppx","xnt!"]
decoded_list = []
for word in words_list:
for char in word:
word = word.replace(char, DICT_CODE.get(char))
decoded_list.append(word)
print decoded_list
Output
['good', 'day!']
Hope this helps.

Python, how to make program sort title words and normal words?

I need to write a program that would ask for a random sentence, for example: "This is a Sentence."
And it would print out like this:
Title words: This, Sentence
Words: is, a
How do I write such a program? I started and I tried making the start and the end but not sure I am going the right way. So far I have this:
while True:
sentence = ("Please enter a sentence:")
if sentence.title() == True:
for i in range (len(tword)):
print ("Title words: ", tword[i])
print ("Words: ", words[i])
Could anyone give me hints or tips?
You can use istitle method
sentence = input("Please enter a sentence:")
words = []
title = []
for i in sentence.split():
if i.istitle():
title.append(i)
else:
words.append(i)
>>>print('title words:',",".join(title))
title words: This,Sentence
>>>print('words:',",".join(words))
words: is,a
try like this:
>>> my_sentence = "Hello how are you, hello World"
>>> import re
>>> my_sentence = "Hello how are you, hello World"
>>> my_words = re.findall("\w+", my_sentence) #This will find all words
>>> my_words
['Hello', 'how', 'are', 'you', 'hello', 'World']
>>> my_dict = {}
>>> for x in my_words:
... if x[0].isupper(): # check for if words start with uppercase or not
... my_dict['title'] = my_dict.get("title", []) + [x]
... else:
... my_dict['word'] = my_dict.get("word", []) + [x]
...
>>> my_dict
{'word': ['how', 'are', 'you', 'hello'], 'title': ['Hello', 'World']}
your Desired Output:
>>> print "Title: {}\nWord: {}".format(", ".join(my_dict['title']), ", ".join(my_dict['word']))
Title: Hello, World
Word: how, are, you, hello
Try following :
title_array = [word for word in sentence.split() if word.istitle()]
To strip it of from other symbols, more precisely,
title_array = [''.join([c for c in word if c.isalnum()]) for word in sentence.split() if word.istitle()]
With regex,
[''.join([c for c in word if c.isalnum()]) for word in re.split('\W+', sentence) if word.istitle()]
This is the approach I would use using your definition of a title word:
import re
sentence = "This is a Sentence."
titles, words = [], []
for word in re.findall("\w+", sentence):
[words, titles][word[0].isupper()].append(word)
print("Title: {}\nWord: {}".format(", ".join(titles), ", ".join(words)))
Output:
Title: This, Sentence
Word: is, a

Delete words which have 2 consecutive vowels in it

What i want is remove the words which have more than two consecutive vowels in it. So input:
s = " There was a boat in the rain near the shore, by some mysterious lake"
Output:
[boat,rain,near,mysterious]
So here is my code.
I was just wondering if there is any better way to do this or is this efficient enough.And if you can do this with python dict or lists are ok? :) I'm new to python so yeah. :) comments would be nice.
def change(s):
vowel = ["a","e","i","o","u"]
words = []
a = s[:].replace(",","").split()
for i in vowel:
s = s.replace(i, "*").replace(",","")
for i,j in enumerate(s.split()):
if "**" in j:
words.append(a[i])
return words
Alternatively, you could always use regular expressions and list comprehension to get the list of words:
>>> import re
>>> [x for x in s.split() if re.search(r'[aeiou]{2}', x)]
['boat', 'rain', 'near', 'mysterious']
s.split() splits the sentence into a list of words. The expression [x for x in s.split()] considers each word in this list in turn.
The re.search(r'[aeiou]{2}', x) part of the expression searches each word for two consecutive letters from the group [aeiou]. Only if two consecutive vowels are found is the word put in the new list.
using sets:
First method using set.intersection will only find non identical consecutive pairs so oo would not be a match:
s = " There was a boat in the rain near the shore, by some mysterious lake"
vowels = "aeiouAEIOU"
print([x for x in s.split() if any(len(set(x[i:i+2]).intersection(vowels))== 2 for i in range(len(x))) ])
['boat', 'rain', 'near', 'mysterious']
Method 2 uses set.issubset so now identical consecutive pairs will be considered a match.
using set.issubset with a function using the yield from python 3 syntax which might be more appropriate and indeed to catch repeated identical vowels :
vowels = "aeiouAEIOU"
def get(x, step):
yield from (x[i:i+step] for i in range(len(x[:-1])))
print([x for x in s.split() if any(set(pr).issubset(vowels) for pr in get(x, 2))])
Or again in a single list comp:
print([x for x in s.split() if any(set(pr).issubset(vowels) for pr in (x[i:i+2] for i in range(len(x[:-1]))))])
Finally make vowels a set and check if it is a set.issuperset of any pair of chars:
vowels = {'a', 'u', 'U', 'o', 'e', 'i', 'A', 'I', 'E', 'O'}
def get(x, step):
yield from (x[i:i+step] for i in range(len(x[:-1])))
print([x for x in s.split() if any(vowels.issuperset(pr) for pr in get(x, 2))])
Using pairwise iteration:
from itertools import tee
def pairwise(iterable):
a, b = tee(iter(iterable))
next(b)
return zip(a,b)
vowels = 'aeiouAEIOU'
[word for word in s.split() if any(
this in vowels and next in vowels for this,next in pairwise(word))]
Use regular expressions instead:
import re
s = 'There was a boat in the rain near the shore, by some mysterious lake'
l = [i for i in s.split(' ') if re.search('[aeiou]{2,}', i)]
print ' '.join(l) # back to string
Using product instead:
from itertools import product
vowels = 'aiueo'
comb = list(product(vowels, repeat=2))
s = " There was a boat in the rain near the shore, by some mysterious lake"
def is2consecutive_vowels(word):
for i in range(len(word)-1):
if (word[i], word[i+1]) in comb:
return True
return False
print [word for word in s.split() if is2consecutive_vowels(word)]
# ['boat', 'rain', 'near', 'mysterious']
or if you don't need to use any external library:
vowels = 'aeiou'
def is2consecutive_vowels2(word):
for i in range(len(word)-1):
if word[i] in vowels and word[i+1] in vowels:
return True
return False
print [word for word in s.split() if is2consecutive_vowels2(word)]
# ['boat', 'rain', 'near', 'mysterious']
This one is even quicker than regex solution!
a=[]
def count(s):
c=0
t=s.split()
for i in t:
for j in range(len(i)-1):
w=i[j]
u=i[j+1]
if u in "aeiou" and w in "aeiou":
c+=1
if(c>=1):
a.append(i)
c=0
return(a)
print(count("There was a boat in the rain near the shore, by some mysterious lake"))

unexpected character after line continuation character in if statement

This is my code for removing vowels from given string.My code shows unexpected character after line continuation character in if statement condition?can anyone help
def anti_vowel(text):
r=len(text)
new=[]
for i in range(0,r):
if lower.text[i]!='a' and lower.text[i]!='e'
and lower.text[i]!='i' and lower.text[i]!='o' and lower.text[i]!='u':
new.append(text[i])
print " ".join(new)`
I modified your function to use set and list comprehension:
def anti_vowel(text):
vowels = {'a', 'e', 'i', 'o', 'i'}
new = [a_letter for a_letter in text if a_letter not in vowels]
return "".join(new)
print(anti_vowel("Hey You!"))
#prints: Hy Yu!
I simply tried to prove your work using this - Is that what you had in mind?
text="The brown fox quickly jumped over the lazy dog"
list_of_vow = ['a','e','i','o','u']
new_word = text;
for x in list_of_vow:
new_word = new_word.replace(x,'')
print(new_word)

Categories

Resources