Counting the number of vowels - python

Trying to print no. of vowels. When I run this code I get 1,2,3,4 I intend to print only 4. Where is my mistake and how would I correct it?
vowels='a','e','i','o','u'
s= 'hellohello'
count = 0
for letters in s:
if letters in vowels:
count+=1
print (count)

You're mostly right, but you're printing in the loop rather than at the end.
for letters in s:
if letters in vowels:
count+=1
# de indent to close the loop
print (count)

count should be out of for loop.So that it prints only once.
vowels='a','e','i','o','u'
s= 'hellohello'
count = 0
for letters in s:
if letters in vowels:
count+=1
print (count)

Related

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.

How to write code where you don't define a variable

I am trying to solve this problem below
Assume s is a string of lower case characters. Write a program that
counts up the number of vowels contained in the string s. Valid vowels
are: 'a', 'e', 'i', 'o', and 'u'. For example, if s =
'azcbobobegghakl', your program should print:
Number of vowels: 5
I wrote the following code
s='azcbobobegghakl'
count = 0
for vowels in s:
if vowels in 'aeiou':
count += 1
print ('Number of vowels: ' + str(count))
This was not correct. I learned that you should not define "azcbobobegghakl" as s or g or anything else for that matter. Do I need to use a certain function to accomplish this?
You can use a list comprehension and then count the list.
print("Number of vowels: {}".format(len([vowel for vowel in input() if vowel in "aeiou"])))
The question is asking to count the number of vowels in any string, not just the example azcbobobegghakl, therefore you should replace the fixed string with an input().
What you have seems to do the task required by the question, however, if the do want it in the form of a function you can restate the code you already have as a function:
def count_vowels(s):
count = 0
for vowels in s:
if vowels in 'aeiou':
count += 1
print ('Number of vowels: ' + str(count))
Then, you can execute your program with the following:
count_vowels('azcbobobegghakl')
s = str(input("Enter a phrase: "))
count = 0
for vowel in s:
if vowel in 'aeiou':
count += 1
print("Number of vowels: " + str(count))
This seems to work on python but it is not the right answer.

Vowel counter script not executing

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))]))

Write a function that returns a list for the number of vowels per line

Define a function lineStats() that takes one parameter:
1. paragraph, a string of words and white spaces
The function returns a list containing the number of vowels in each line.
for example,
t="Apple\npear and kiwi"
print(lineStats(t))
[2,5]
This is what I have. I've gotten the output to be 7 but not to be able to make it 2,5. I tried to make a counter for each line but that didn't work, any suggestions?
def lineStats(paragraph):
vowels = "AEIOUaeiou"
for line in paragraph:
for word in line:
for letter in word:
if letter in vowels:
counter +=1
else:
continue
return counter
t = "Apple\npear and kiwi"
print(lineStats(t))
Here's an adaption of your current code
def lineStats(paragraph):
vowels = "AEIOUaeiou"
counter = []
current_line_count = 0
newline = "\n"
for letter in paragraph:
if letter in vowels:
current_line_count += 1
elif letter == newline:
counter.append(current_line_count)
current_line_count = 0
counter.append(current_line_count)
return counter
t="Apple\npear and kiwi"
def lineStats(p):
#find vowels in each line and sum the occurences using map
return map(sum, [[1 for e in f if e in "AEIOUaeiou"] for f in p.split('\n')])
lineStats(t)
Out[601]: [2, 5]
Try this
Create this function
def temp(x):
return sum(v for k, v in Counter(x).items() if k.lower() in 'aeiuo')
Now
from collections import Counter
print [temp(x) for x in lines.split('\n')]
Changing as little of your code as necessary, other answers offer improvements.
def lineStats(paragraph):
counter = []
vowels = "AEIOUaeiou"
lines = paragraph.split('\n')
for line in lines:
count = 0
for word in line:
for letter in word:
if letter in vowels:
count +=1
else:
continue
counter.append(count)
return counter
t = "Apple\npear and kiwi"
print(lineStats(t)) # [2, 5]
The problem states it wants the result to be a list of counts, so changing counter to be a list that we can append to, then use that list to store the vowel count for each line. That may be the only major change to your code that you need to get the required output.
However, there is the concern of newlines ('\n') in the "paragraph", so we str.split() the paragraph into individual lines before entering the for-loop. This will break the count for each line, instead of the total count that you were getting.

My program for counting how many vowels in a user input sentence doesn't count the same vowel twice. How do i fix this?

print ("Sentence analysis")
Sentence = (input("Please enter a sentence"))
def WordCount(Sentence):
words = (Sentence.count(' ')+1)
print ("There are", words ,"words in this sentence")
WordCount(Sentence)
The code above is fine and used to count how many words in the input sentence.
vowels = ['a','e','i','o','u']
count=0
for v in vowels:
if v in Sentence:
count+=1
print (count)
When running, say if I input a a e i o u would only count 5 vowels whereas there are 6. How do I fix this?
Use .count():
count = 0
for v in vowels:
count += Sentence.count(v)
Or better:
count = sum(Sentence.count(v) for v in vowels)
That is because you are doing your check in reverse. You want to go over your sentence and check each letter against vowels:
vowels = ['a','e','i','o','u']
count=0
for s in Sentence:
if s in vowels:
count+=1
print (count)
For a nicer approach, however, check out #zondo's answer.
The problem you are having is that when you loop through v in vowels and check if v is in Sentence it only checks if it v is present in Sentance not how many times. If you flip it around so it checks through Sentence first and check each letter to see if it is in vowels it will check all of the letters in Sentence.
print ("Sentence analysis")
Sentence = (input("Please enter a sentence"))
vowels = ['a','e','i','o','u']
count=0
for letter in Sentence:
if letter in vowels:
count+=1
print (count)
For the first code can be simplified the WordCount() function as:
print(len(Sentence.split()))
or:
import re
print(len(re.findall(r'\w+', Sentence)))

Categories

Resources