Vowel counter script not executing - python

vowel = "aeiou"
for i in range(0:len(s)):
if s[i] in vowel == True
count += 1
print("Number of vowels: "+str(count))
The above code doesn't throw any errors in Spyder. I am taking an online course, s is a predefined variable which contains a string. Here I defined s as "big black car"
I have to count the vowels in the string.
When I press enter after typing the code in, I am moved to the next line, nothing happens, I am prompted for more input.
What am I doing wrong?

Working code for you:
s="big black car"
vowel = "aeiou"
count = 0
for i in range(len(s)):
if s[i] in vowel:
count += 1
print("Number of vowels: "+str(count))
Note: First of all, you should use range (len(s)). Second thing is that s[i] in vowel == True will return False. You can easy check it in python console.
>>> 'a' in 'a'
True
>>> 'a' in 'a' == True
False
>>> ('a' in 'a') == True
True
According to my best knowledge Python firstly execute 'a' == True that gives False, then execute 'a' in False. That's why condition is False. Extra parentheses fix that problem.
EDIT: tripleee point that you can use range(len(s)) :).

You need to fix the following:
Get rid of the 0:
Replace the == True with a :
Indent the count += 1 4 spaces to the right
So your code should look as follows:
vowel = "aeiou"
for i in range(len(s)):
if s[i] in vowel:
count += 1
print("Number of vowels: "+str(count))
You can further reduce it to:
vowel = "aeiou"
for i in range(len(s)):
count += s[i] in vowel
print("Number of vowels: "+str(count))
And then further reduce it to:
vowel = "aeiou"
count = sum([s[i] in vowel for i in range(len(s))])
print("Number of vowels: "+str(count))
And then further reduce it to:
vowel = "aeiou"
print("Number of vowels: "+str(sum([s[i] in vowel for i in range(len(s))])))
And then further reduce it to:
vowel = "aeiou"
print("Number of vowels: ", sum([s[i] in vowel for i in range(len(s))]))
And then further reduce it to:
print("Number of vowels: ", sum([s[i] in "aeiou" for i in range(len(s))]))

Related

Add a character before two consecutive vowels in a sentence? Python

I'm trying to add the letter 'X' before each vowel in a string or sentence, however, when there is a repeated vowel, the letter 'X' should only be written once. For example, the word 'speeding' should look like this 'spXeedXing' but i'm getting 'spXeXedXing'.
I know why I'm getting this problem but don't know where to go from here to make it work.
Code below
def vowels(string):
newString = ""
for letter in string:
if letter in "aeiou":
newString += "X" + letter
else:
newString += letter
print(newString)
if __name__ == "__main__":
vowels("speeding")
>>> import re
>>> re.sub('([aeiou]+)','X\g<1>','speeding')
'spXeedXing'
>>>
You should create a new variable to track the previous letter in string. Check if the letters are continuous and only add X if the previous char is not the same as the current char.
def vowels(string):
newString = ""
i = 0 # Create a counter variable
for letter in string:
if (letter in "aeiou" and letter != string[i-1]) or (letter in "aeiou" and i == 0 and letter == string[i-1]): # Change this condition.
i += 1
newString += "X" + letter
else:
newString += letter
i += 1 # Increment counter variable
print(newString)
if __name__ == "__main__":
vowels("speeding")
Output:
spXeedXing
Other test cases:
vowels("oompaloompas")
XoompXalXoompXas
vowels("eerie")
XeerXiXe
You can let a regex do all the state-machine hard work...
To prepend 'X' to any number of consecutive vowels:
import re
s = 'speeding'
>>> re.sub(r'([aeiou]+)', r'X\1', s)
'spXeedXing'
To prepend 'X' only to the same repeating vowel:
s = 'speeding'
>>> re.sub(r'(([aeiou])\2*)', r'X\1', s)
'spXeedXing'
s = 'toaster'
>>> re.sub(r'(([aeiou])\2*)', r'X\1', s)
'tXoXastXer'
Here is a simple non-regex version:
def vowels(word):
new_word = ""
prev = "" # no previous letter at first
for letter in word:
if letter in "aeiou" and letter != prev:
new_word += "X" + letter
else:
new_word += letter
prev = letter # keep to avoid insertion for repeats
return new_word
if __name__ == "__main__":
print(vowels("speeding"))
print(vowels("eerie"))
print(vowels("aaaaaaaaaaaaaargh"))
producing
spXeedXing
XeerXiXe
Xaaaaaaaaaaaaaargh
you should try checking the previous letter in the string to see if it is the same letter as the current index
def vowels(string):
newString = ""
for i in range(len(string)):
if string[i] in "aeiou":
if string[i - 1] == string[i]:
newString += string[i]
else:
newString += "X" + string[i]
else:
newString += string[i]
print(newString)

Printing the vowels and the vowel count in a string

I will have to define a function that takes a person's full name and finds the total number of vowels in that input. And I need to output every vowel including the total
number of vowels found. If the name does not contain any vowel then my function should print
“No vowels in the name!”. Two sample inputs and their corresponding outputs are given below:
Sample input:
(Steve Jobs)
(XYZ)
Sample Output:
Vowels: e, e, o. Total number of vowels: 3
No vowels in the name!
I know it is quite a simple program, but I am facing some difficulties in printing an output as shown in the Sample Output. Here's my incomplete code:
def vowels(full_name):
for i in full_name:
count = 0
if i == 'a' or i == 'A' or i == 'e' or i == 'E' or i == 'i' or i =='I' or i == 'o' or i == 'O' or i == 'u' or i == 'U':
count += 1
print(i, end= ',')
print('Total number of vowels: ', count)
How can I write a clean program to get the expected output? I'm really lost at this point
Some things that may be helpful: As the comments have already pointed out, your long chain of ors can be shortened by using in to check for substring membership:
>>> "a" in "AEIOUaeiou"
True
>>> "b" in "AEIOUaeiou"
False
>>>
You can use filter to create a collection of vowels - only retaining those characters which are vowels:
def is_vowel(char):
return char in "AEIOUaeiou"
vowels = list(filter(is_vowel, "Bill Gates"))
print(vowels)
Output:
['i', 'a', 'e']
>>>
You know that if vowels is empty, you can print "No vowels in the name!". If it's not empty, you can print your other message, and use str.join on vowels to print the vowels, seperated by commas:
print(", ".join(vowels))
Output:
i, a, e
>>>
The number of vowels found is just the length of vowels.
vowels = "aeiou"
def is_vowel(char):
return char in vowels
def count_vowels(word):
vowels = [char for char in word if is_vowel(char.lower())]
return len(vowels)
print('Total number of vowels:', count_vowels("Steve Jobs"))

How to check if one character is next to another (Flesch index)?

I'm learning to work with strings and my project is to calculate the number of syllables in a sentence.
I'm given some code that calculates the syllables by adding to the variable, syllables += 1, for each vowel. But the end product is wrong because consecutive vowels should only count as a single +1. For example the word "certain" should return two syllables, not three. There is more to it than this but it's not relevant to my question.
Here is how I solved the problem, with an explanation below:
syllables = 0
vowels = "aeiouAEIOU"
vowelContainer = "" # Part of my added code for solution. Create some container to hold
# a representation of consecutive vowels.
for word in text.split():
for vowel in vowels:
syllables += word.count(vowel)
for ending in ['es', 'ed', 'e']:
if word.endswith(ending):
syllables -= 1
if word.endswith('le'):
syllables += 1
for vowel in word: # My added code for solution: rest of lines that follow
if vowel == vowel in vowels: # I fill in the container with Ts and Fs to create a string
vowelContainer += "T" # that I can then check for consecutive vowels.
else:
vowelContainer += "F"
count2ConsecutiveVowels = vowelContainer.count("TT") # I count how many times there are two
count3ConsecutiveVowels = vowelContainer.count("TTT") # or three vowels in the word.
syllables = syllables - count2ConsecutiveVowels - count3ConsecutiveVowels # I subtract the count
vowelContainer = "" # from total syllables
# At the end of the loop I empty the container for the next word.
I managed to come up with a solution, but it is messy. Is there a simpler way to do this?
I think this code should work:
vowels = "aeiouAEIOU"
text = "certain"
syllables_count = 0
if len(text) == 1:
if text[0] in vowels:
syllables_count += 1
else:
for i in range(len(text) - 1):
if text[i] in vowels and text[i+1] not in vowels:
syllables_count += 1
elif text[i] in vowels and i+1 == len(text) - 1:
syllables_count += 1
print(syllables_count)
In order to solve the problem of consecutive vowels you mentioned above, and get the correct number of syllables, I suggest using a regular expression as in the following example:
import re # put in the beginning to import regular expression module
word='certaaaaiin' # just for example
a=re.findall(r'[aeiouAEIOU](?![aeiouAEIOU])',word)
syllables =len(a)
print(syllables)
# output is 2
In this method, any number of consecutive vowels is considered as one in counting
in the regular expression [aeiouAEIOU](?![aeiouAEIOU]), it selects any vowel in the list, in case of that vowel does not have another one after.
vowels = "aeiou"
count = 0
with open("/home/doofinschmurts/PycharmProjects/Practice_001/text.txt", "r") as text:
text = text.read()
for character in range(len(text) - 1):
if text[character] in vowels and text[(character + 1)] not in vowels and text[character - 1] not in vowels:
count += 1
elif text[character] in vowels and text[character + 1] in vowels and text[character - 1] not in vowels:
count += 1
elif text[character] in vowels and text[character + 1] in vowels and text[character + 2] in vowels and text[character - 1] not in vowels:
count += 1
print(count)
I'm new to coding but this script works and the main "jist" is in the long if statements. This wont be the best answer; however, if any veterans wouldn't mind critiquing me also.
Every time you encounter a vowel, you need to increment the syllables counter by 1. Otherwise, you can ignore it.
Try this and see if this meets your needs.
text = input('Enter your word(s) :')
syllables = 0
vowels = "aeiou" #no need to check for upper and lower
for word in text.split():
vowel_found = False #initialize vowel_found to False and check if the world has vowels
for char in word: #iterate thru each char in the word
if not vowel_found and char.lower() in vowels: #for every new vowel found, increment syllables by 1
syllables +=1
vowel_found = True
else:
vowel_found = False #reset to increment counter again
print (syllables)
Here's the output I got:
Enter your word(s) :syllables
2
Enter your word(s) :certain
2
Enter your word(s) :book
1
Enter your word(s) :case
2
Enter your word(s) :Heart
1
Let me know if this code fails. I would like to improve this.

struggling with string characters

I am trying to solve an exercise regarding strings in Python. The exercise says: Write a function that takes a string word and returns a list of strings containing the sound elements of the given word.
A sound element is a maximal sequence of 1 or more consonants followed by 1 or more vowels. In other words, i am supposed to iterate over a string of characters and split it everytime a vowel is followed by a consonant.
Example:
the following string given in input:
S = 'unconditionally'
should return the following list
L = ['u','nco','ndi','tio','na','lly']
In order to solve the exercise, i have written the following function:
def split_words(S):
string = ''
syllables = []
vowels = ['a','e','i','o','u','j','y']
for i in range(len(S)):
if S[i] not in vowels:
string += S[i]
elif S[i] in vowels and S[i+1] not in vowels:
string += S[i]
syllables.append(string)
string = ''
return syllables
Which should be able to solve it. The problem is that i get an index-out-of-range error everytime i run the program. I know the issue is in the elif statement which i don't know how to get rid of.
Is there any way to solve this exercise without importing any external libraries?
Any help will be appreciated
You iterate till the index of the last character :
for i in range(len(S)):
and you have this line:
elif S[i] in vowels and S[i+1] not in vowels:
if i is the last index of S, then it will throw error on S[i+1]
Edit: You can use this:
def split_words(S):
string = ''
syllables = []
vowels = ['a','e','i','o','u','j','y']
for i in range(len(S)):
if S[i] not in vowels:
if len(string) == 0 or not string[-1] in vowels: #here I check if length of string is 0
#in this case I can append letter to it. And also if last letter (`string[-1]`) isn't a vowel,
#then also I can add this letter to string
string += S[i]
else: # if last letter was vowel then we reset string.
syllables.append(string)
string = ''
string += S[i]
else:
string += S[i]
syllables.append(string)
return syllables
We can further simplify code, because we have string += S[i] in every block of if-else:
def split_words(S):
string = ''
syllables = []
vowels = ['a','e','i','o','u','j','y']
for i in range(len(S)):
if S[i] not in vowels and len(string) > 0 and string[-1] in vowels:
syllables.append(string)
string = ''
string += S[i]
syllables.append(string)
return syllables

Removing ending vowels from a word

This function receives a string as input and should return the number of syllables in the string.
This function has following conditions:
1. Number of syllables is equal to the number of vowels
2. Two or more consecutive vowels count only as one.
3. One or more vowels at the end of the word are not counted.
This is what I've so far but clearly I'm still missing a lot. I'm not sure how to continue here, so I hope you guys can help.
def syllables(word):
vowels = ['a','e','i','o','u','y']
# Delete ending vowel of the word since they don't count in number of syllables
# I've no idea how to remove all ending vowels though
word = word[:-1]
# List with vowels that appear in the word
vowelsList = [x for x in vocals if x in word]
N = []
for i in word:
if i in vowels:
N += i
N = len(N)
return N
print(syllables("bureau"))
# Should print "1" but prints "3" instead
I suggest you the following simple code:
def syllables(word):
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
N = 0
previousLetterIsAVowel = False
# Perform a loop on each letter of the word
for i in word.lower():
if i in vowels:
# Here it is a vowel
# Indicate for the next letter that it is preceded by a vowel
# (Don't count it now as a syllab, because it could belong to a group a vowels ending the word)
previousLetterIsAVowel = True
else:
# Here: it is not a vowel
if previousLetterIsAVowel:
# Here it is preceded by a vowel, so it ends a group a vowels, which is considered as a syllab
N += 1
# Indicate for the next letter that it is not preceded by a vowel
previousLetterIsAVowel = False
return N
print(syllables("bureau")) # it prints 1
print(syllables("papier")) # it prints 2
print(syllables("ordinateur")) # it prints 4
print(syllables("India")) # it prints 1
I also provide a one-line style solution using regex, easily readable too if you know a little bit about regex. It simply counts the number of groups of consecutive vowels that are followed by a consonant:
import re
def syllables(word):
return len(re.findall('[aeiouy]+[bcdfghjklmnpqrstvwxz]', word.lower()))
To check the last vowel you can try something like this (I wouldn't iterate as you're going to loose whole syllables): -> EX: Italian word "Aia" (threshing floor)
if word[-1] in vocals:
word=word[:-1]
-- sorry but I didn't manage to put 'code' into comments so a posted an answer
I would go for:
def syllables(word):
def isVowel(c):
return c.lower() in ['a','e','i','o','u','y']
# Delete ending vowel of the word since they don't count in number of syllables
while word and isVowel(word[-1]):
word = word[:-1]
lastWasVowel = False
counter = 0
for c in word:
isV = isVowel(c)
# skip multiple vowels after another
if lastWasVowel and isV:
continue
if isV:
# found one
counter += 1
lastWasVowel = True
else:
# reset vowel memory
lastWasVowel = False
return counter
Stolen from LaurentH:
print(syllables("bureau")) # prints 1
print(syllables("papier")) # prints 2
print(syllables("ordinateur")) # prints 4
print(syllables("I")) # prints 0
I think we have return 1 if there is previousLetterIsAVowel and N returns 0. Example word Bee.
In Addition to Laurent H. answer
if N == 0 and previousLetterIsAVowel:
return 1
else:
return N

Categories

Resources