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)
Related
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'))
splitText(text) where text is a string and return the list of the words by splitting the string text.
See example below:
sampleText = "As Python's creator, I'd like to say a few words about its origins.”
splitText(sampleText)
['As', 'Python', 's', 'creator', 'I', 'd', 'like', 'to', 'say', 'a', 'few', 'words', 'about', 'its', 'origins']
You must NOT use the method split() from the str type, however other methods >from the class are allowed. You must not use python library such as string.py.
This is my code:
def split(text):
final_lst = ""
length = len(text)
for x in range(length):
if text[x].isalpha() == True:
final_lst = final_lst + text[x]
else:
final_lst = final_lst + ", "
final_len = len(final_lst)
for a in range(final_len):
if final_lst[:a] == " " or final_lst[:a] == "":
final_lst = "'" + final_lst[a]
if final_lst[a:] == " " or final_lst[a:] == ", ":
final_lst = final_lst[a] + "'"
elif final_lst[:a].isalpha() or final_lst[a:].isalpha():
final_lst[a]
print(final_lst)
split(sampleText)
When I run it I get this:
'A
I've tried lots of things to try and solve.
First of all, your function name is wrong. You have split(text) and the exercise specifically calls for splitText(text). If your class is graded automatically, for example by a program that just loads your code and tries to run splitText(), you'll fail.
Next, this would be a good time for you to learn that a string is an iterable object in Python. You don't have to use an index - just iterate through the characters directly.
for ch in text:
Next, as #Evert pointed out, you are trying to build a list, not a string. So use the correct Python syntax:
final_list = []
Next, let's think about how you can process one character at a time and get this done. When you see a character, you can determine whether it is, or is not, an alphabetic character. You need one more piece of information: what were you doing before?
If you are in a "word", and you get "more word", you can just append it.
If you are in a "word", and you get "not a word", you have reached the end of the word and should add it to your list.
If you are in "not a word", and you get "not a word", you can just ignore it.
If you are in "not a word", and you get "word", that's the start of a new word.
Now, how can you tell whether you are in a word or not? Simple. Keep a word variable.
def splitText(text):
"""Split text on any non-alphabetic character, return list of words."""
final_list = []
word = ''
for ch in text:
if word: # Empty string is false!
if ch.isalpha():
word += ch
else:
final_list.append(word)
word = ''
else:
if ch.isalpha():
word += ch
else:
# still not alpha.
pass
# Handle end-of-text with word still going
if word:
final_list.append(word)
return final_list
sampleText = "As Python's creator, I'd like to say a few words about its origins."
print(splitText(sampleText))
Output is:
['As', 'Python', 's', 'creator', 'I', 'd', 'like', 'to', 'say', 'a', 'few', 'words', 'about', 'its', 'origins']
Next, if you sit and stare at it for a while you'll realize that you can combine some of the cases. It boils down nicely- try turning it inside out by moving the outer if to the inside, and see what you get.
To me, it looks like you are complicating things too much, basically all you need to do is to go through the text char by char, and combining them to words, once you find empty space you separate it and add it to the result array. After you run out of text you just return the array.
def splittext(text):
result = []
word = ""
for i in text:
if i != " ":
word += i
else:
result.append(word)
word = ""
result.append(word)
return result
This should work:
smapleText = 'As Python\'s creator, I\'d like to say a few words about its origins.'
def split(text):
result =[]
temp=""
length = len(text)
for x in range(length):
if text[x].isalpha():
temp = temp+text[x]
else:
result.append(temp)
temp=""
print result
split(smapleText)
Can you cheat with regular expressions?
import re
sampleText = "As Python's creator, I'd like to say a few words about its origins."
result = re.findall(r'\w+', sampleText)
>>> result
['As', 'Python', 's', 'creator', 'I', 'd', 'like', 'to', 'say', 'a', 'few', 'words', 'about', 'its', 'origins']
def stringSplitter(string):
words = []
current_word = ""
for x in range(len(string)):
if string[x] == " ":
words.append(current_word)
current_word = ""
else:
current_word += string[x]
return words
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.
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
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"))