我的代码到目前为止,但由于我迷失了它并没有做任何接近我想要它做的事情:
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个元音。
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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]
答案 3 :(得分: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
答案 4 :(得分:0)
如果您检查了下一个字符是空格,则可以使用一个for循环将子字符串保存到字符串数组中。 他们为每个子串,检查是否只有一个a,e,i,o,u(元音),如果是,则添加到另一个数组
aFTER THAT,from另一个数组,用空格和逗号
连接所有字符串答案 5 :(得分: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]
答案 6 :(得分: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)
答案 7 :(得分: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)