如何打印仅含一个元音的单词?

2 投票
8 回答
3521 浏览
提问于 2025-04-17 18:45

这是我目前写的代码,但因为我完全搞不清楚,所以它根本没有做到我想要的效果:

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

因为它们只包含一个元音字母。

8 个回答

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]
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
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

撰写回答