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

我发现您缺少正则表达式令人不安。

这是一个纯正则表达式的解决方案(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

如果您检查了下一个字符是空格,则可以使用一个 for 循环将子字符串保存到字符串数组中。它们对于每个子字符串,检查是否只有一个 a,e,i,o,u (vowels) ,如果是,则添加到另一个数组中

之后,从另一个数组中,用空格和逗号连接所有字符串

于 2013-03-12T02:18:21.600 回答
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 回答