Home > OS >  Counting the number of syllables in a words with the exception that in words that end with "es&
Counting the number of syllables in a words with the exception that in words that end with "es&

Time:01-15

I want to count the number of syllables in a word, by counting the number of vowels in that word, and not counting the last "e" in the words that end with "ed" and "es".

I ran the following code, but I'm not able to handle that exception:

import re
vowelRegex = re.compile(r'[aeiouAEIOU^ed$|^es$]')
vowelRegex.findall('RoboCoped eatsed babyes food. BABY FOOD.')

This is the output i got:

['o',
 'o',
 'o',
 'e',
 'd',
 'e',
 'a',
 's',
 'e',
 'd',
 'a',
 'e',
 's',
 'o',
 'o',
 'd',
 'A',
 'O',
 'O']

CodePudding user response:

You can use

(?i)(?!e[ds]\b)[aeiou]
(?![eE][DdsS]\b)[aeiouAEIOU]

See the regex demo. Details:

  • (?i) - enable case insensitive matching
  • (?!e[ds]\b) - no match if there are ed or es followed with a word boundary immediately on the right
  • [aeiou] - one of the letters listed in the char set.

See the Python demo:

import re
vowelRegex = re.compile(r'(?!e[ds]\b)[aeiou]', re.I)
print(vowelRegex.findall('RoboCoped eatsed babyes food. BABY FOOD.'))
print(vowelRegex.sub(r'(\g<0>)', 'RoboCoped eatsed babyes food. BABY FOOD.'))

Output:

['o', 'o', 'o', 'e', 'a', 'a', 'o', 'o', 'A', 'O', 'O']
R(o)b(o)C(o)ped (e)(a)tsed b(a)byes f(o)(o)d. B(A)BY F(O)(O)D.
  •  Tags:  
  • Related