user1775726
user1775726

Reputation: 23

python regex-only one vowel, but no other vowels

given the string below,

sentences = "He is a student. She is a teacher. They're students, indeed. Babies sleep much. Tell me the truth. Bell--push it!"

how can i print the words in the "sentences" that contain only one "e", but no other vowels? so, basically, i want the following:

He She Tell me the

my code below does not give me what i want:

for word in sentences.split():
    if re.search(r"\b[^AEIOUaeiou]*[Ee][^AEIOUaeiou]*\b", word):
        print word 

any suggestions?

Upvotes: 0

Views: 1173

Answers (2)

John Gaines Jr.
John Gaines Jr.

Reputation: 11534

Unless you're going for a "regex-only" solution, some other options could be:

others = set('aiouAIOU')
[w for w in re.split(r"[^\w']", sentence) if w.count('e') == 1 and not others & set(w)]

which will return a list of the matching words. That led me to a more readable version below, which I'd probably prefer to run into in a maintenance situation as it's easier to see (and adjust) the different steps of breaking down the sentence and the discrete business rules:

for word in re.split(r"[^\w']", sentence):
    if word.count('e') == 1 and not others & set(word):
        print word

Upvotes: 0

Tebbe
Tebbe

Reputation: 1372

You're already splitting out the words, so use anchors (as opposed to word boundaries) in your regular expression:

>>> for word in sentences.split():
...     if re.search(r"^[^AEIOUaeiou]*[Ee][^AEIOUaeiou]*$", word):
...         print word
He
She
Tell
me
the
>>> 

Upvotes: 1

Related Questions