Python 计算单词末尾的元音

Python 计算单词末尾的元音,python,python-3.x,Python,Python 3.x,编写一个名为voueLendings的函数,该函数以字符串text作为参数 函数voureLendings返回字典d,其中键是文本中某个单词的最后一个字母的所有元音。字母a、e、i、o和u是元音。没有其他字母是元音。d中每个键对应的值是以该元音结尾的所有单词的列表。任何单词在给定列表中都不应出现一次以上。文本中的所有字母都是小写 以下是正确输出的示例: >>> t = 'today you are you there is no one alive who is you-er

编写一个名为voueLendings的函数,该函数以字符串text作为参数

函数voureLendings返回字典d,其中键是文本中某个单词的最后一个字母的所有元音。字母a、e、i、o和u是元音。没有其他字母是元音。d中每个键对应的值是以该元音结尾的所有单词的列表。任何单词在给定列表中都不应出现一次以上。文本中的所有字母都是小写

以下是正确输出的示例:

>>> t = 'today you are you there is no one alive who is you-er than you'
>>> vowelEndings(t)
{'u': ['you'], 'o': ['no', 'who'], 'e': ['are', 'there', 'one', 'alive']}
这就是我到目前为止所做的:

def vowelEndings(text):
    vowels = 'aeiouAEIOU'
    vowelCount = 0
    words = text.split()

    for word in words:
        if word[0] in vowels:
            vowelCount += 1

    return vowelCount

t = 'today you are you there is no one alive who is you-er than you'
print(vowelEndings(t))
输出:

5

所做的是计算每个单词开头的元音,但它应该计算每个单词结尾的元音。此外,它应该打印出元音和元音所指的单词,就像问题中的一样。我需要帮助。

你很接近了。缺少的方面有:

  • 要提取最后一个字母,请使用
    word[-1]
  • 您需要创建一个带有元音键的词典
  • 字典值应设置为
    set
    ,以避免重复
经典的Python解决方案是使用集合。defaultdict:

from collections import defaultdict

t = 'today you are you there is no one alive who is you-er than you'

def vowelEndings(text):
    vowels = set('aeiou')
    d = defaultdict(set)

    for word in text.split():
        final = word[-1]
        if final in vowels:
            d[final].add(word)

    return d

print(vowelEndings(t))

defaultdict(set,
            {'e': {'alive', 'are', 'one', 'there'},
             'o': {'no', 'who'},
             'u': {'you'}})

你试着用什么来检查单词的结尾而不是开头?您是否尝试构建要返回的词典?您将需要一个dict来设置值。获取单词的最后一个字母应该相当容易,只需执行单词[-1],这会给你结果中的关键,Dict认为用我所拥有的东西它会起作用,我尝试了不同的方法使这个程序起作用,但这是我能使它起作用的最接近的方法
{v:[w for w in t.split()if w.endswith(v)]v in'aeiou}
试试看……我现在明白了。我完全忘记了集合和单词[-1]。谢谢你这帮了大忙