2

これまでの私のコードですが、私はとても迷っているので、私がやりたいことに近いことは何もしません:

vowels = 'a','e','i','o','u','y'
#Consider 'y' as a vowel

input = input("Enter a sentence: ")

words = input.split()
if vowels == words[0]:
    print(words)

したがって、次のような入力の場合:

"this is a really weird test"

印刷するだけにしたい:

this, is, a, test

母音が 1 つしか含まれていないためです。

4

8 に答える 8

5

これを試して:

vowels = set(('a','e','i','o','u','y'))

def count_vowels(word):
    return sum(letter in vowels for letter in word)

my_string = "this is a really weird test"

def get_words(my_string):
    for word in my_string.split():
        if count_vowels(word) == 1:
            print word

結果:

>>> get_words(my_string)
this
is
a
test
于 2013-03-12T02:21:02.863 に答える
5

別のオプションは次のとおりです。

import re

words = 'This sentence contains a bunch of cool words'

for word in words.split():
    if len(re.findall('[aeiouy]', word)) == 1:
        print word

出力:

This
a
bunch
of
words
于 2013-03-12T02:32:01.100 に答える
4

すべての母音を単一の母音に変換し、その母音を数えることができます。

import string
trans = string.maketrans('aeiouy','aaaaaa')
strs = 'this is a really weird test'
print [word for word in strs.split() if word.translate(trans).count('a') == 1]
于 2013-03-12T02:20:50.087 に答える
3
>>> s = "this is a really weird test"
>>> [w for w in s.split() if len(w) - len(w.translate(None, "aeiouy")) == 1]
['this', 'is', 'a', 'test']

母音のない単語が必要かどうかはわかりません。== 1もしそうなら、単に< 2

于 2013-03-12T02:41:44.397 に答える
0

これを試して:

vowels = ('a','e','i','o','u','y')
words = [i for i in input('Enter a sentence ').split() if i != '']
interesting = [word for word in words if sum(1 for char in word if char in vowel) == 1]
于 2013-03-12T03:44:25.890 に答える
0

私はここでとても素敵なコードを見つけました、そして私は私の醜いものを見せたいです:

v = 'aoeuiy'
o = 'oooooo'

sentence = 'i found so much nice code here'

words = sentence.split()

trans = str.maketrans(v,o)

for word in words:
    if not word.translate(trans).count('o') >1:
        print(word)
于 2013-03-14T07:07:02.390 に答える
0

あなたの正規表現の欠如は気がかりです。

これは、単純な正規表現のみのソリューション(ideone)です。

import re

str = "this is a really weird test"

words = re.findall(r"\b[^aeiouy\W]*[aeiouy][^aeiouy\W]*\b", str)

print(words)
于 2013-04-11T23:14:38.763 に答える
0

次の文字がスペースであることを確認した場合は、1 つの for ループを使用して部分文字列を文字列配列に保存できます。部分文字列ごとに、 a,e,i,o,u (母音) が 1 つしかないかどうかを確認し、ある場合は別の配列に追加します

その後、別の配列から、すべての文字列をスペースとコンマで連結します

于 2013-03-12T02:18:21.600 に答える