Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequence of vowels count

Tags:

python

regex

nlp

This is not a homework question, it is an exam preparation question.

I should define a function syllables(word) that counts the number of syllables in A word in the following way:

• a maximal sequence of vowels is a syllable;

• a final e in a word is not a syllable (or the vowel sequence it is a part Of).

I do not have to deal with any special cases, such as a final e in a One-syllable word (e.g., ’be’ or ’bee’).

>>> syllables(’honour’)
2
>>> syllables(’decode’)
2
>>> syllables(’oiseau’)
2

Should I use regular expression here or just list comprehension ?

like image 333
Gusto Avatar asked Feb 26 '23 22:02

Gusto


1 Answers

I find regular expressions natural for this question. (I think a non-regex answer would take more coding. I use two string methods, 'lower' and 'endswith' to make the answer more clear.)

import re
def syllables(word):
    word = word.lower()
    if word.endswith('e'):
        word = word[:-1]
    count = len(re.findall('[aeiou]+', word))
    return count

for word in ('honour', 'decode', 'decodes', 'oiseau', 'pie'):
    print word, syllables(word)

Which prints:

honour 2
decode 2
decodes 3
oiseau 2
pie 1

Note that 'decodes' has one more syllable than 'decode' (which is strange, but fits your definition).

Question. How does this help you? Isn't the point of the study question that you work through it yourself? You may get more benefit in the future by posting a failed attempt in your question, so you can learn exactly where you are lacking.

like image 121
Steven Rumbalski Avatar answered Mar 08 '23 00:03

Steven Rumbalski