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」を1つだけ含み、他の母音を含まない「文」の単語を出力するにはどうすればよいですか? したがって、基本的には、次のものが必要です。

彼 彼女 教えて

以下の私のコードでは、私が望むものは得られません:

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 に答える