I wrote this function to count the syllables in a word using Python to complete an exercise.
The exercise's text is:
Return the number of syllables in the given word, according to this rule: Each contiguous sequence of one or more vowels is a syllable, with the following exception: a lone "e" at the end of a word is not considered a syllable unless the word has no other syllables. You should consider y a vowel.
I also disagree with the text because using the given instructions the syllable count for the word "example" are 2 and should be 3.
But, as discussed in the comments, the exercise text is the one that I implemented and would like to get suggestions and improvements for.
def count_syllables(word):
word = word.lower()
counter = 0
is_previous_vowel = False
for index, value in enumerate(word):
if value in ["a", "e", "i", "o", "u", "y"]:
if index == len(word) - 1:
if value == "e":
if counter == 0:
counter += 1
else:
counter += 1
else:
if is_previous_vowel == True:
counter += 1
is_previous_vowel = False
break
is_previous_vowel = True
else:
if is_previous_vowel == True:
counter += 1
is_previous_vowel = False
print ("In \"{}\" I count {} syllables".format(word, counter))
count_syllables("coding")
1 Answer 1
As a good practice to promote code reuse, the function should return
a numeric result. The print()
should be done by the caller.
Constantly referring to is_previous_vowel
is tedious. There are a couple of solutions you could use involving itertools
. In particular, groupby()
and zip_longest()
could be useful.
Ultimately, the simplest solution is to use a regular expression to declare what you are looking for: one or more consecutive vowels ('[aeiouy]+'
), but not an e
at the end ('(?!e$)
).
import re
def count_syllables(word):
return len(
re.findall('(?!e$)[aeiouy]+', word, re.I) +
re.findall('^[^aeiouy]*e$', word, re.I)
)
-
\$\begingroup\$ This is a masterpiece \$\endgroup\$Pitto– Pitto2019年07月15日 07:50:09 +00:00Commented Jul 15, 2019 at 7:50
ord
function you can convert any character to its 8 bit integer representation. Then you could write instead offor
anwhile loop
till end character is found (0x00
), where your counter would then becounter += 1 if (ord(word[i]) & 97 == 97 else 0
. You can see what integer representations of your vowel letters are by going into console and justlist(map(ord, 'aeiouy'))
. With while loop you can save in speed by not assigning length of string. GKeyWords: Bitwise operators. \$\endgroup\$e
forms a syllable; treatment ofy
is too simplistic (say,beyond
). However I am curious how did you come up with 4 syllables inexample
. Nevertheless, the problem statement is what has to be implemented. \$\endgroup\$