python正则表达式只有一个元音,但没有其他元音

时间:2012-11-15 21:12:03

标签: python regex for-loop

给出下面的字符串,

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

如何打印只包含一个“e”但没有其他元音的“句子”中的单词? 所以,基本上,我想要以下内容:

他告诉我

下面的代码没有给我我想要的东西:

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

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您已经拆分了单词,因此请在正则表达式中使用锚点(而不是单词边界):

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

答案 1 :(得分:0)

除非您要使用“仅限正则表达式”的解决方案,否则其他一些选项可能是:

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

将返回匹配单词的列表。这导致我在下面看到一个更易阅读的版本,我可能更喜欢在维护情况下遇到这种情况,因为它更容易看到(并调整)分解句子和离散业务规则的不同步骤:

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