0

给定下面的字符串,

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 

有什么建议么?

4

2 回答 2

1

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

>>> for word in sentences.split():
...     if re.search(r"^[^AEIOUaeiou]*[Ee][^AEIOUaeiou]*$", word):
...         print word
He
She
Tell
me
the
>>> 
于 2012-11-15T21:18:19.120 回答
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
于 2012-11-15T22:01:28.697 回答